day_6.23py线程
进程之间不能共享全局变量
线程之间共享全局变量,线程函数中的局部变量不是共享的!!
#--*utf- 8*-- from threading import Thread import time g_num = 100 def work1(): global g_num for i in range(3): g_num += 1 print("-----in work1,g_num is %d-----"%g_num) def work2(): global g_num print("-------in work2 ,g_num is %d-----"%g_num) print("---------线程创建之前g_num is %d---"%g_num) t1 = Thread(target=work1) t1.start() #延时一会,保证t1线程中的事情做完 time.sleep(1) t2 = Thread(target=work2) t2.start()
关于互斥锁,解决线程占用的问题!!!
上锁的代码越少越好!该加的时候才加!
#--*utf- 8*-- from threading import Thread ,Lock import time g_num = 0 def work1(): global g_num #上锁, 这个线程和work2线程都在抢着 对这个锁进行上锁,如果由1方成功的上锁 #那么导致一方会堵塞(一直等待)到这个锁被解开位置 mutex.acquire() for i in range(100000): g_num += 1 #解锁 #用来对mutex指向的这个锁, 进行解锁,,只要开了锁,那么接下来会让所有 #因为这个锁 被锁上的锁 而堵塞的线程,进行抢着上锁 mutex.release() print("-----in work1,g_num is %d-----"%g_num) def work2(): global g_num #上锁 mutex.acquire() for i in range(100000): g_num += 1 #解锁 mutex.release() print("-------in work2 ,g_num is %d-----"%g_num) #创建一把互斥锁,这个锁默认是没有上锁的 mutex =Lock() def main(): t1 = Thread(target=work1) t1.start() #延时一会,保证t1线程中的事情做完 # time.sleep(1) #取消屏蔽之后,再次运行程序 t2 = Thread(target=work2) t2.start() if __name__ == '__main__': main()
同步的应用!就是一个接着一个
#--*utf-8*--- #同步的应用! #2018-6-23 19:51:59 from threading import Thread,Lock from time import sleep class Task1(Thread): def run(self): while True : if lock1.acquire(): print("------Task1----------") sleep(0.5) #给Task2开锁! lock2.release() class Task2(Thread): def run(self): while True: if lock2.acquire(): print("------Task2----------") sleep(0.5) #给Task3开锁 lock3.release() class Task3(Thread): def run(self): while True: if lock3.acquire(): print("------Task3----------") sleep(0.5) lock1.release() #使用Lock创建出的锁默认没有"锁上" lock1 = Lock() #创建另外一个锁,并且锁上 lock2 = Lock() lock2.acquire() #创建另外一个锁,并且"锁上" lock3 = Lock() lock3.acquire() t1 = Task1() t2 = Task2() t3 = Task3() t1.start() t2.start() t3.start()