0
from threading import Thread
import threading
import time


def procesa1():
    lock = threading.Lock()
    lock.acquire()

    for i in range(3):
        print(threading.get_ident())
    lock.release()


if __name__ == "__main__":
    hilos = []
    for i in range(5):
        hilos.append(Thread(target=procesa1))
    for thread in hilos:
        thread.start()

The 3 print in each thread should come out in a row, shouldn't they?

A thread WINS the lock, prints its 3 outputs in a row (not interspersed with those of the other threads) and then the 3 outputs of the next thread.

This is an example of the multiple random outputs:

13108
13108
13108
12780
12780
12780
7756 // what?
6844
6844
6844
7756 // what?
7756 // what?
11936 //good
11936 //good
11936 //good, they are consecutive

The lock is supposed to be for a critical "atomic" section accessed by one thread AT A TIME.

What am I losing?

1 Answers1

1

The lock doesn't help to synchronize threads because each thread is creating its own lock. You need to create a single lock and pass it as an argument to each thread, so they can share it.

This works as expected (I simplified the syntax using with):

def procesa1(lock):
    with lock:
        for i in range(3):
            print(threading.get_ident())


if __name__ == "__main__":
    lock = threading.Lock()
    hilos = []
    for i in range(5):
        hilos.append(Thread(target=procesa1, args=(lock,)))
    for thread in hilos:
        thread.start()

Output:

34360446720
34360446720
34360446720
34360360224
34360360224
34360360224
[....]
sj95126
  • 6,520
  • 2
  • 15
  • 34
  • hi @sj95126 thanks. when we use critical sections, is it 100% guaranteed that instructions (in this case, for example, printouts) from other threads will not interleave with the current thread that has the lock? –  Oct 31 '22 at 15:44
  • 2
    @GeorgeMeijer: That is the intention of the lock - the other threads will block waiting for the lock to be released. I'm not sure what level of guarantee can be provided beyond that. If you're looking for "cannot fail under any circumstances because lives depend on it" you need a language designed for that purpose. – sj95126 Oct 31 '22 at 15:49
  • great @sj95126, thank you very much, now I understand + 1 and marked as useful answer –  Oct 31 '22 at 15:56