Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Event objects in python with a thread?

I have a main python script which starts a thread running in the background.

poll = threading.Thread(target=poll_files, args=myargs)

I want my main script to wait until something specific happens in my poll thread. I want to use an Event object. So in my main script, I do:

trigger = threading.Event()

and when I want to wait:

trigger.wait()

My question is, inside my poll thread, how do I set the Event to True? I know I do:

trigger.set()

but do I need to also have trigger = threading.Event() inside my poll thread?

like image 446
user1566200 Avatar asked Jul 06 '15 13:07

user1566200


1 Answers

Pass the Event object to the thread target function so that they are shared between main thread and the pool thread:

def poll_files(....., trigger):
    ....
    trigger.set()

# main thread
trigger = threading.Event()
poll = threading.Thread(target=poll_files, args=myargs + (trigger,))
...
trigger.wait()
like image 87
falsetru Avatar answered Sep 28 '22 07:09

falsetru