join() 在调用结束前,主线程不会结束
不加的话,主线程会在子线程结束前继续执行(并行);加了join(),主线程会等待子线程结束后在继续执行下去(串行)
#python3
#main print number ,stop after son thread stop
#son thread print id
import time , threading
def doWaiting():
print('start waiting:', time.strftime('%H:%M:%S'))
time.sleep(3)
print('stop waiting', time.strftime('%H:%M:%S'))
thread1 = threading.Thread(target = doWaiting)
thread1.start()
time.sleep(1)
#确保线程thread1已经启动
print('start join')
thread1.join()
#将一直堵塞,直到thread1运行结束。
print('end join')
lock = threading.Lock() #创建锁
lock.acquire() #锁定
#do sth
lock.release()
释放
或者
with lock:
#do sth
用一个例子来演示会更加清晰