Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your description seems to imply you don't want the threads to execute concurrently, which would bring into question why you're using threading in the first place. </p> <p>I sense two possible answers as to why you'd want to do this.</p> <p>The first possibility is that you are trying to prevent your threads from working on some sort of shared resource at the same time. If this is the case, you probably want to use threading.Lock or threading.RLock to lock your critical code section. (the below example is coded for python 2.5+, you will need to use explicit lock acquire/releasing on older pythons)</p> <pre><code>from __future__ import with_statement # only needed on python 2.5 from threading import Lock lock = Lock() def worker1(): #noncritical code with lock: pass # critical code in here def worker2(): with lock: critical_code </code></pre> <p>This will not enforce any sort of ordering, however. When multiple threads try to acquire a lock, all but one will block (and which one acquires the lock next is not determinate)</p> <p>The fact that you mention ordering makes me think you instead have some sort of producer-consumer cycle going on. That is, one thread generates some output which the next needs to work with. You can use queue.Queue to provide data between threads and have them wake up to gobble the next bit of data.</p> <pre><code>from queue import Queue one_to_two = Queue(maxsize=10) def worker1(): while i_have_some_data_stream: data = get_data_from_somewhere() modified_data = munge_data_somehow(data) one_to_two.put(modified_data) #blocks only if queue is currently full def worker2(): while True: data = one_to_two.get() # blocks until data available # do something with data # Optionally, put this newly processed data into the next queue. </code></pre> <p>Queues are a powerful primitive that let you pass messages between threads and implement bounded producer-consumers. If that is your use case, the queue will be more efficient than trying to manually synchronize your thread's ordering.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload