Kautenja / nes-py

A Python3 NES emulator and OpenAI Gym interface
MIT License
235 stars 63 forks source link

It seems that render() works even inside thread. #91

Open ravijo opened 1 year ago

ravijo commented 1 year ago

It seems that render() works even inside a thread. Just remember to get rid of the exception by removing the following lines:

https://github.com/Kautenja/nes-py/blob/b6f4e26a96cf1dc2329b3b45b9f785dd7dbb30c6/nes_py/_image_viewer.py#L25-L28

A sample code is shown below:

import os
os.environ['OMP_NUM_THREADS'] = '1'

import threading
import gym_super_mario_bros
from gym_super_mario_bros.actions import SIMPLE_MOVEMENT
from nes_py.wrappers import JoypadSpace

def dummy_fun(steps):
    import numpy as np
    rng = np.random.default_rng(steps)
    sum = 0.0
    for _ in range(steps):
        rfloat = rng.random()
        sum += rfloat
    print(f'sum {sum}')

def do_something(steps):
    print('inside do_something')
    env = JoypadSpace(gym_super_mario_bros.make('SuperMarioBros-1-1-v0', new_step_api=False), SIMPLE_MOVEMENT)
    done = True
    for _ in range(steps):
        if done:
            state = env.reset()
        state, reward, done, info = env.step(env.action_space.sample())
        env.render()
    print(f'state shape {state.shape}')
    env.close()

def main():
    steps = 5000
    thread1 = threading.Thread(
        target=dummy_fun,
        args=(
            steps,
        ),
    )
    thread1.start()

    thread2 = threading.Thread(
        target=do_something,
        args=(
            steps,
        ),
    )
    thread2.start()

    thread1.join()
    thread2.join()

if __name__ == '__main__':
    main()

Below is the screenshot: Screenshot

ravijo commented 1 year ago

I created a pull request. let me know if additional checking is required: https://github.com/Kautenja/nes-py/pull/92