79543989

Date: 2025-03-29 22:46:07
Score: 0.5
Natty:
Report link

A simplified version of Alex answer

import threading
import time

lock=threading.Lock()
def thread1cb():
    lock.acquire() # thread1 acquires lock first
    time.sleep(1)
    print("hello")
    lock.release()
def thread2cb():
    time.sleep(0.1)
    lock.acquire() # thread2 will wait on this line until thread1 has released the lock it acquired
    print("there")
    lock.release()


thread1=threading.Thread(target=thread1cb)
thread2=threading.Thread(target=thread2cb)
thread1.start()
thread2.start()
thread1.join() # As long as thread1 acquires & releases the lock first, you could safely remove this line. threading.Thread(...).join() waits until the target function of the thread has returned.
thread2.join()

Output will be:

hello
there

If you comment out the lock.acquire() & lock.release() lines, it will instead print:

there
hello

Docs: https://docs.python.org/3/library/threading.html#threading.Lock.acquire
https://docs.python.org/3/library/threading.html#using-locks-conditions-and-semaphores-in-the-with-statement

Reasons:
  • Probably link only (1):
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: Willy Wonka