关于python多线程模块的Condition,设计了一个实验

下面这个实验看懂了,就明白Condion和其中的wait及notify的原理了:

import threading
import time

condi = threading.Condition()
N =1

def tar01():
    global N
    with condi:
        print('%s is started'%threading.current_thread().name)
        print(N)
        N +=1
        time.sleep(0.1)
        print('in %s,wait01 is going to work'%threading.current_thread().name)
        condi.wait()
        print('in %s,notify 01 is going to  work'%threading.current_thread().name)
        condi.notify()
        print('in %s,notify 01 finished'%threading.current_thread().name)


def tar02():
    global N
    with condi:
        print('%s is started'%threading.current_thread().name)
        print(N)
        N +=1
        time.sleep(0.1)
        print('in %s,notify 02 is going to work'%threading.current_thread().name)
        condi.notify()
        print('in %s,wait 02 is going to  work'%threading.current_thread().name)
        condi.wait()
        print('in %s,wait 02 finished'%threading.current_thread().name)

# t1 = threading.Thread(target= tar01) # 这两个线程即使没有被使用,也被创建了出来,并占用了头两个线程的编号
# t2 = threading.Thread(target= tar02)
for i in range(2):
    threading.Thread(target=tar01).start()
    threading.Thread(target=tar02).start()
print('+++++++++++++++finished+++++++++++++++')
# 运行结果证明:在循环执行两次两个tar01和tar02时,tar02唤醒的原因是tar02.wait()了
# D:\python\python.exe "D:/Projects/常用算法 - python/Mult_thread/td.py"
# Thread-1 is started
# 1
+++++++++++++++finished+++++++++++++++
# in Thread-1,wait01 is going to work
# Thread-2 is started
# 2
# in Thread-2,notify 02 is going to work
# in Thread-2,wait 02 is going to  work
# Thread-3 is started
# 3
# in Thread-3,wait01 is going to work
# Thread-4 is started
# 4
# in Thread-4,notify 02 is going to work
# in Thread-4,wait 02 is going to  work
# in Thread-1,notify 01 is going to  work
# in Thread-1,notify 01 finished
# in Thread-2,wait 02 finished
# in Thread-3,notify 01 is going to  work
# in Thread-3,notify 01 finished
# in Thread-4,wait 02 finished
#
# Process finished with exit code 0

结论就是

1. Condition锁定的线程是不阻塞后续代码执行的,也就是说,当后续代码执行完毕之后,Condition锁定的线程仍然还在内存中继续执行着。所以如果后续代码有对文件读写的动作,并且这个动作涉及到了Condition锁定了的线程给出的结果,就要特别注意。但是如果用mutex = threading.Lock(),然后再老老实实的去t.join()的方式阻塞线程就没问题,然后再
在target函数内部做with mutex:就不会有问题。


2.对于使用同一个Condtion限制的target函数,这些线程都是同时被阻塞,然后文本位置排在第一个的target函数先执行,遇到condi.wait()就休眠。然后,当第一个函数休眠的时候,第二个函数自动被唤醒,然后遇到condi.wait()就休眠。以此类推

3.所有的进程都是在最后一起退出内存的

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值