How to force the execution of another thread

I have one main thread that does some pretty intense CPU work. The thread must hold the lock for all of its calculations.

Then there are several other threads that sometimes require the same lock for a short time.

How can I make the main main thread sometimes allow other threads to execute without slowing it down if there are no other threads?

Periodic

lock.release()
time.sleep(x)
lock.acquire()

for some x, it transfers control to another thread, but slows down the main thread if there are no other threads.

On the other hand, without calling sleep()GIL, it seems to intervene here. Since the main thread has a GIL when it executes release(), the other thread apparently cannot immediately return from acquire(). Therefore, the main thread continues its own method acquire(), and other threads never get locked unless the GIL switch matches that I release my own lock.

What is the correct solution to this problem? Is there any way to force the release of GIL? Basically, I need some kind of magical piece of code that ensures that in the next script test the second thread always gets the lock first:

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()
+3
source share
2 answers

GIL , .

Unix sched_yield(). Python; .

usleep(0) select() , . Windows, Sleep (0). time.sleep(0) .

+3

Source: https://habr.com/ru/post/1766564/


All Articles