2022年5月7日 23:11 by wst
python高级线程是操作系统运算调度的最小单位,它被包含在进程之中,是进程中的实际运作单位。
import threading
import time
def process():
for i in range(3):
time.sleep(1)
print("thread name is %s" % threading.current_thread().name)
if __name__ == "__main__":
print("主线程开始")
threads = [threading.Thread(target=process) for i in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print("-------主线程结束------")
逻辑:模拟多人购票,刚开始有100张电影票,10个人同时抢购。
from threading import Thread, Lock
import time
n = 100
mutex = Lock()
def task():
global n
mutex.acquire()
temp = n
time.sleep(0.1)
n = temp - 1
print("购买成功,剩余%d张电影票" % n)
mutex.release()
if __name__ == "__main__":
tl = []
for i in range(10):
t = Thread(target=task)
tl.append(t)
t.start()
for t in tl:
t.join()
from queue import Queue
import random
import threading
import time
class Producer(threading.Thread):
""" 生产者 """
def __init__(self, name, queue: 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: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())
if __name__ == "__main__":
print("------主线程开始-------")
queue = Queue()
producer = Producer('Producer', queue)
consumer = Consumer('Consumer', queue)
producer.start()
consumer.start()
producer.join()
consumer.join()
print("=======主线程结束========")