1、线程模式代码
#!/usr/bin/python #_*_coding:utf-8_*_ import threading import time def Producer(): print ‘chef : 等人来买包子。。。‘ event.wait() event.clear() print ‘sb is coning for baozi...‘ print ‘chef : making a baozi for sb...‘ time.sleep(3) print ‘chef : 你的包子好了‘ event.set() def Consumer(): print ‘maxi : 去买包子‘ event.set() time.sleep(1) print ‘maxi : waiting for baozi tobe readly‘ event.wait() print ‘哎呀,真好吃‘ event = threading.Event() p = threading.Thread(target=Producer) c = threading.Thread(target=Consumer) p.start() c.start()
运行结果:
2、怎样调用自己的线程类
代码如下:
#!/usr/bin/python #_*_coding:utf-8_*_ from threading import Thread import time class MyThread(Thread): #调用我自己的线程方法前,必须先调用父类的run()方法; def run(self): print ‘myThread‘ #Thread.run(self) #启用父类的run(),只有这样才能调用自己的线程函数 super(MyThread, self).run() def Bar(): print ‘bar‘, t1 = MyThread(target = Bar) #我的线程方法Bar()函数; t1.start() print ‘over‘
运行结果:
3、线程安全
代码如下:
#!/usr/bin/python #_*_coding:utf-8_*_ import threading import time num = 0 def run(n): time.sleep(1) samp.acquire() #锁上 global num num += 1 print ‘%d\n‘ % num samp.release() #释放锁 #lock = threading.Lock() #锁机制, samp = threading.BoundedSemaphore(4) #信号量 for i in range(1000): t = threading.Thread(target = run, args = (i,)) t.start()
因为上面给了4个信号量,就是可以同时最多有4个进程抢占资源;
运行结果:
当我们把信号量改为1时,就相当于独占,此时结果肯定就是1000了;
时间: 2024-10-12 09:06:28