多线程

待添加 条件变量 condition

个人代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

#生产者消费者
import threading # , _thread ()python2x是thread
import time
import queue #python2x是Queue
import random

mutex = threading.Lock() #等价于_thread.allocate_lock(),也等价于_thread.allocate()
myq = queue.Queue(10)
num = range(10)

class Producer(threading.Thread):
def run(self):
global myq, num
for i in range(30):
time.sleep(0.3)
if not myq.full() and mutex.acquire():
info = random.choice(num)
myq.put(info)
print("put in data: ", info, "; queue size", myq.qsize())
mutex.release()

class Consumer(threading.Thread):
def run(self):
global myq, num
for i in range(30):
time.sleep(1)
if not myq.empty() and mutex.acquire():
info = myq.get()
print("get out data: ", info, "; queue size", myq.qsize())
mutex.release()

def main():
print ('main')
p = Producer()
c = Consumer()
p.start()
c.start()

if __name__ == '__main__':
main()

别人家的代码【滑稽】:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import thread, threading
import urllib2
import time, random
import Queue

share_queue = Queue.Queue() #共享队列
my_lock = thread.allocate_lock()
class Producer(threading.Thread) :

def run(self) :
products = range(5)
global share_queue
while True :
num = random.choice(products)
my_lock.acquire()
share_queue.put(num)
print "Produce : ", num
my_lock.release()
time.sleep(random.random())

class Consumer(threading.Thread) :

def run(self) :
global share_queue
while True:
my_lock.acquire()
if share_queue.empty() : #这里没有使用信号量机制进行阻塞等待,
print "Queue is Empty..."
my_lock.release()
time.sleep(random.random())
continue
num = share_queue.get()
print "Consumer : ", num
my_lock.release()
time.sleep(random.random())

def main() :
producer = Producer()
consumer = Consumer()
producer.start()
consumer.start()

if __name__ == '__main__':
main()

转载自 链接地址: http://www.jianshu.com/p/86b8e78c418a

个人博客 欢迎来访: http://blog.zj2626.com