Kautenja/nes-py

It seems that render() works even inside thread.

ravijo opened this issue · 1 comments

ravijo commented

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

import threading
if threading.current_thread() is not threading.main_thread():
msg = 'rendering from python threads is not supported'
raise RuntimeError(msg)

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

I created a pull request. let me know if additional checking is required:
#92