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

  1. 线程的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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值