多线程简单案例 - join( ) -lock()

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')

参考:https://blog.csdn.net/goldxwang/article/details/77838072

 

lock = threading.Lock()  #创建锁

lock.acquire() #锁定

#do sth

lock.release()

释放 

或者

with lock:

  #do sth

posted @ 2018-05-26 11:05  littlevigra  阅读(168)  评论(1编辑  收藏  举报