#!/usr/bin/python
# -*- coding:utf8 -*-
from threading import Thread, Lock
import random
def test_thread():
# 线程间的通信
# 使用锁来控制共享资源的访问
a = 0
n = 10000000
lock = Lock()
def imcr(n):
global a
for i in range(n):
lock.acquire() # 可以写成with lock:
a += 1 # a+=1
lock.release()
def decr(n):
for i in range(n):
global a
lock.acquire()
a -= 1
lock.release()
t = Thread(target=imcr, args=(n,))
t2 = Thread(target=decr, args=(n,))
t.start()
t2.start()
t.join()
t2.join()
print(a)
# 多线程的消费者与生产者模式
# from threading import Thread
from queue import Queue
q = Queue(3)
class Producter(Thread):
def __init__(self, queue):
super().__init__()
self.queue = queue
def run(self):
while True:
item = random.randint(0, 99)
self.queue.put(item)
print('已产生%s' % item)
class Consumer(Thread):
def __init__(self, queue):
super().__init__()
self.queue = queue
def run(self):
while True:
item = self.queue.get()
print(item)
self.queue.task_done() # 告诉队列这个任务执行完成
product = Producter(q)
consumer = Consumer(q)
product.start()
consumer.start()
# 注意,mgr=Manger() q.mgr.Queue()
# 进程版本的需要加一个input()或者是
# producter.join consumer.join() 因为一旦主进程结束,代码就不会继续运行了