I have an application that gets locked in a loop in one thread in order to perform some kind of task. There is also a second thread that also wants to get a lock from time to time. The problem is that this second thread hardly gets the opportunity to do its job, since the first is almost always blocked by the first. I hope the following code clarifies what I'm trying to say:
import time from threading import Lock, Thread lock = Lock() def loop(): while True: with lock: time.sleep(0.1) thread = Thread(target=loop) thread.start() before = time.time() lock.acquire() print('Took {}'.format(time.time() - before))
If the application print you will notice that it needs more than 0.1 s. But sometimes it happens that he just waits endlessly. I tested this in both Python 2.7.11 and Python 3.4.3 on Debian Linux 8, and it works the same.
This behavior is counterintuitive to me. In the end, when the lock.acquire lock lock.acquire in the loop , lock.acquire already waiting for it to be released, and it should immediately receive the lock. But instead, it looks like the loop gets the lock first, although he did not expect it to be released at the time of release at all.
The solution I found is to sleep between each iteration of the loop in an unlocked state, but this does not seem to me an elegant solution and does not explain to me what is happening.
What am I missing?
Jakub source share