0

I am trying to learn how mutex works in multithread application, but I have some doubts. In my case I have thread which read from device, thread which write to device and synchronization thread. In sync thread I have a timer in this form:

def CheckConnection(self):
        .   .   .
            threading.Timer(1, self.CheckConnection).start()

This timer runs periodically CheckConnection function.

Could you tell me:

  1. When thread is locked (acquired) it means that thread stops execution and waits? this is sth like pause?

  2. What will happen when I start synchronization thread, my checkConnection function executes and timer starts, after it synchronization-thread is locked... This will stop the timer and execution of CheckConnection function?

pb.
  • 321
  • 3
  • 4
  • 21

1 Answers1

0
  1. The mymutex.acquire() call will block the thread calling it until the mutex is available, then lock the mutex (so blocking any other thread which calls mymutex.acquire()), then return so the thread can continue execution. The call to mymutex.release() releases/unlocks the mutex and the oldest thread blocked on mymutex.acquire() gets to lock the mutex and return, i.e. unblocks this other thread.
  2. Is self.CheckConnection the same function as you are defining in def CheckConnection()? So you're trying to get the CheckConnection function called every 1 (in your case) second?. There is a nice description of how to do this in the top answer here Python threading.timer - repeat function every 'n' seconds

Each thread using the mutex should be doing something like:

themutex.acquire()
try:
    print('Do some stuff')
finally:
    themutex.release()

In general, the code between acquire and release, i.e. 'do some stuff', should be as quick as possible because the maximum duration of any of these sections of code where mutex has been acquired is also the maximum time another thread will be blocked (unless several threads are blocked, when obviously the maximum delay can get even longer).

Community
  • 1
  • 1