Enable thread-safe operation
masterBy default, pyvirtualdisplay is not thread-safe because it modifies the global os.environ["DISPLAY"] variable.
To use multiple displays in different threads, you must:
- Set
manage_global_env=Falsein theDisplay(orSmartDisplay) constructor. - Manually pass the display environment variables to your child processes using
disp.env().
import threading
from pyvirtualdisplay.smartdisplay import SmartDisplay
from easyprocess import EasyProcess
def thread_function(index):
# manage_global_env=False prevents modifying os.environ globally
with SmartDisplay(manage_global_env=False) as disp:
cmd = ["xmessage", str(index)]
# Use disp.env() to provide the correct DISPLAY to the process
with EasyProcess(cmd, env=disp.env()):
img = disp.waitgrab()
img.save(f"xmessage{index}.png")
t1 = threading.Thread(target=thread_function, args=(1,))
t2 = threading.Thread(target=thread_function, args=(2,))
t1.start()
t2.start()
t1.join()
t2.join()