我好像贝壳吧 关注:97贴子:5,970
  • 4回复贴,共1

我也来水一贴

只看楼主收藏回复

@我好像贝壳 , 还记得操作系统里讲的P/V操作、生产者/消费者问题、信号量巴拉巴拉的东西么?那个时候是用伪代码写的,无聊就用python实现一下了(纯属水贴):
+--------------------------------------------------Code-I-------------------------------------------------+
__author__ = 'streethacker'
#-*- coding: utf-8 -*-
import threading
import time
product = None
con = threading.Condition()
class Producer(threading.Thread):
def __init__(self):
super(Producer, self).__init__()
def run(self):
global product, con
if con.acquire():
while True:
if product is None:
print "producing..."
product = "something"
con.notify()
con.wait()
time.sleep(2)
class Consumer(threading.Thread):
def __init__(self):
super(Consumer, self).__init__()
def run(self):
global product, con
if con.acquire():
while True:
if product is not None:
print "consuming..."
product = None
con.notify()
con.wait()
time.sleep(2)
t1 = Producer()
t2 = Consumer()
t1.start()
t2.start()
+-------------------------------------------------------------------------------------------------------------+
+------------------------------------------------Code-II---------------------------------------------------+
__author__ = 'streethacker'
#-*- coding: utf-8 -*-
import threading
import time
semaphore = threading.Semaphore(2)
def func():
print "%s acquire semaphore..." % threading.currentThread().getName()
if semaphore.acquire():
print "%s get the semaphore..." % threading.currentThread().getName()
time.sleep(2)
print "%s release semaphore..." % threading.currentThread().getName()
semaphore.release()
t1 = threading.Thread(target= func)
t2 = threading.Thread(target= func)
t3 = threading.Thread(target= func)
t4 = threading.Thread(target= func)
t1.start()
t2.start()
t3.start()
t4.start()
+-------------------------------------------------------------------------------------------------------------+


IP属地:上海1楼2013-11-12 23:09回复
    哎哟我去,缩进全没了......


    IP属地:上海2楼2013-11-12 23:13
    收起回复
      表示完全看不懂


      IP属地:福建3楼2013-11-12 23:27
      回复

          字


        IP属地:福建4楼2013-11-12 23:28
        回复