您的位置:首页 > 理论基础 > 计算机网络

3.7 学网络编程 threading线程的join deamon方法 锁,死锁,递归锁

2018-03-07 18:24 507 查看
线程的join deamon方法

#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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: