I am starting with multi-threads in python (or at least it is possible that my script creates multiple threads). would this algorithm be the right usage of a Mutex? I haven't tested this code yet and it probably won't even work. I just want processData to run in a thread (one at time) and the main while loop to keep running, even if there is a thread in queue.
from threading import Thread
from win32event import CreateMutex
mutex = CreateMutex(None, False, "My Crazy Mutex")
while(1)
t = Thread(target=self.processData, args=(some_data,))
t.start()
mutex.lock()
def processData(self, data)
while(1)
if mutex.test() == False:
do some stuff
break
Edit: re-reading my code I can see that it is grossly wrong. but hey, that's why I am here asking for help.
This is the solution I came up with:
Output:
I don't know why you're using the Window's Mutex instead of Python's. Using the Python methods, this is pretty simple:
But note, because of the architecture of CPython (namely the Global Interpreter Lock) you'll effectively only have one thread running at a time anyway--this is fine if a number of them are I/O bound, although you'll want to release the lock as much as possible so the I/O bound thread doesn't block other threads from running.
An alternative, for Python 2.6 and later, is to use Python's
multiprocessing
package. It mirrors thethreading
package, but will create entirely new processes which can run simultaneously. It's trivial to update your example:I would like to improve answer from chris-b a little bit more.
See below for my code:
In your first run if you set
thread_safe = False
in while loop, mutex will not be used, and threads will step over each others in print method as below;but, if you set
thread_safe = True
and run it, you will see all the output comes perfectly fine;hope this helps.
You have to unlock your Mutex at sometime...