Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to force execution of a different thread
    primarykey
    data
    text
    <p>I have one main thread that does some rather CPU intensive operation. The thread has to hold a lock for all its calculations.</p> <p>Then there are some other threads which occasionally require the same lock for brief amounts of time.</p> <p>How can I force the main the main thread to occasionally allow the other threads to execute without slowing it down if there are no other threads?</p> <p>A periodic</p> <pre><code>lock.release() time.sleep(x) lock.acquire() </code></pre> <p>for some x would pass control to another thread, but slow the main thread down if there are no other threads.</p> <p>On the other hand, without the <code>sleep()</code> call the GIL seems to interfere here. Since the main thread has the GIL when it executes <code>release()</code>, the other thread is apparently not able to return from <code>acquire()</code> immediately. Therefore, the main thread continues with its own <code>acquire()</code> method and the other threads never get the lock unless a GIL switch happens to coincide exactly with me releasing my own lock.</p> <p>What's the proper solution for this problem? Is there a way to force a GIL release? Basically I want some magic piece of code that makes sure that in the following test script the second thread always gets the lock first:</p> <pre><code>import threading import time class t1 (threading.Thread): def run(self): print "Second thread waiting for lock" lock.acquire() print "Second thread got lock" lock.release() lock = threading.Lock() lock.acquire() t = t1() t.start() time.sleep(1) lock.release() time.sleep(0) # this works very often, but not all the time lock.acquire() print "Main thread got lock" lock.release() </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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