3.7 学网络编程 threading线程的join deamon方法 锁,死锁,递归锁
2018-03-07 18:24
507 查看
线程的join deamon方法
2.线程和全局变量之间的故事–锁,死锁,递归锁
#join 阻塞的是所在的地方,等待线程结束才继续向下执行 import threading import time def foo(n): print('yanga11ang,foo%s'%n) time.sleep(3) def bar(n): print('bar%s'%n) time.sleep(2) #第一种直接调用方式,先创建线程 t1=threading.Thread(target=foo,args=(1,)) t2=threading.Thread(target=bar,args=(2,)) t1.setDeamon(True) # 守护线程,主进程结束,子线程就会结束, t1.start() t2.start() t1.join() #t1结束了才能继续 threading.current_thread() # 线程的名字,区分各个子线程和主线程 threading.active_count() #活着的线程,包含主线程 #第二种用类来创造线程 import threading import time class Mythread(threading.Thread): def __init__(self,num): threading.Thread.__init__(self) self.num=num def run(self): prin('running on number:%s'%self.num) time.sleep(3)
2.线程和全局变量之间的故事–锁,死锁,递归锁
import time import threading def addNum(): global num num-=1 #temp=num #num=temp-1 #time.sleep(1) num=100 thread_list=[] for i in range(100): t=threading.Thread(target=addNum) t.start() thread_list.append(t) for t in thread_list: t.join() print(num) #0 #如果把函数换成#的,不一定还是0 #解决方案 加锁 r=threading.Lock() def addNum(): global num r.acquire() #加锁 temp=num num=temp-1 time.sleep(1) r.release() #解锁 线程不会在用切换到同样的锁的线程 #------------------------------------------------------ import threading,time class myThread(threading.Thread): def __init__(self,name): self.name=name def doA(self): lockA.acquire() #lock.acquire() print(self.name,'gotlockA',time.ctime()) time.sleep(3) lockB.acquire() #lock.acquire() #lock 两次的意义: 锁住他调用的函数,防止被修改 print(self.name,'gotlockB',time.ctime()) lockB.release() #lock.acquire() lockA.release() #lock.acquire() def doB(self): lockB.acquire() #如果b锁没有没用到的话,它可以用线程 #lock.acquire() print(self.name,'gotlockB',time.ctime()) time.sleep(2) lockA.acquire() #lock.acquire() print(self.name,'gotlockA',time.ctime()) lockA.release() #lock.acquire() lockB.release() #lock.acquire() def run(self): self.doA() self.doB() lockA=threading.Lock() lockB=threading.Lock() #可能会造成死锁现象 #lock=threading.RLock() #所有的锁都一样 threads=[] for i in range(5): thread.
相关文章推荐
- 线程的笔记1 wait yield join interrupt deamon 死锁使用方法
- 网络编程——线程同步和线程死锁
- linux网络编程----->线程死锁
- 多线程编程:线程死锁的原因以及解决方法
- 网络编程(45)—— windows平台下销毁线程的四种方法
- 多线程编程-线程间通信-join方法的使用(六)
- 网络编程(42)—— windows平台下创建线程的四种方法(一)
- 网络编程(44)—— windows平台下创建线程的四种方法(三) 工作者线程和CWinThread线程类管理
- 3.6 学网络编程 线程进程 多进程解决方法
- python 线程中join方法的使用
- Java线程中的join方法
- 非阻塞TCP套接字的要点 发表于 2015-04-22 | 分类于 网络编程 | 套接字的默认状态是阻塞的。如果一个套接字不能立即完成相应的调用,那么该线程就会被投入睡眠,等待相应的操
- Java 多线程 (PART VII) 使用join()方法保证线程的执行顺序
- 使用Python中的线程进行网络编程的入门教程
- Java 网络编程[Elliotte R.H.] 中对InputStream.markSupported()方法的误解
- Java网络编程从入门到精通(2):创建InetAddress对象的四个静态方法
- [Python]多线程, 进程和线程, join()方法, 数组和链表
- Python THREADING模块中的JOIN()方法深入理解
- 线程中的join方法
- iOS UI 15 网络编程下载 图片 音乐 大文件 视频 get/ post方法