Python语法之线程思维导图
无情
阅读:708
2021-03-31 13:38:17
评论:0
Python3 功能代码:
import io
import sys
import threading,time,random
from queue import Queue
sys.stdout = io.TextIOWrapper(sys.stdout.detach(),encoding='utf-8')
# 线程实现方式一:使用threading 模块创建线程
def process():
for i in range(3):
time.sleep(1)
print("当前线程名称为 %s" % threading.current_thread().name)
print("---主线程开始---")
threads = [threading.Thread(target=process) for i in range(4)]
# 线程启动
for t in threads:
t.start()
# 线程等待
for t in threads:
t.join()
print("---主线程结束---")
# 线程实现方式二:Thread 子类创建线程
class subThread(threading.Thread):
def run(self):
for i in range(3):
time.sleep(1)
msg = "子线程" + self.name + "执行,i =" + str(i)
print(msg)
print("----主线程开始---")
one = subThread()
two = subThread()
one.start()
two.start()
one.join()
two.join()
print("----主线程结束---")
# 互斥锁
n = 100
def task():
global n
mutex.acquire()
temp = n
time.sleep(0.2)
n = temp -1
print('购票成功,剩余%d张电影票' %n)
mutex.release()
print("----开始购票---")
mutex = threading.Lock()
t_l = []
for i in range(10):
t = threading.Thread(target=task)
t_l.append(t)
t.start()
for t in t_l:
t.join()
print("----购票结束--")
# 队列在线程之间的通信
class Producer(threading.Thread):
def __init__(self, name, queue):
threading.Thread.__init__(self,name = name)
self.data = queue
def run(self):
for i in range(5):
print("生产者%s将产品%d加入队列中!"%(self.getName(),i))
self.data.put(i)
time.sleep(random.random())
print("生产者%s完成"%self.getName())
class Consumer(threading.Thread):
def __init__(self, name, queue):
threading.Thread.__init__(self,name = name)
self.data = queue
def run(self):
for i in range(5):
val = self.data.get()
print("消费者%s将产品%d从队列中取出!"%(self.getName(),val))
time.sleep(random.random())
print("消费者%s完成"%self.getName())
print("----生产/消费者模式开始---")
queue = Queue()
producer = Producer('Producer',queue)
consumer = Consumer('Consumer',queue)
producer.start()
consumer.start()
consumer.join()
producer.join()
print("----生产/消费者模式结束---")
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。