Python 基础入门 10_4 进程线程和协程

"""
线程调用,指当一个线程执行到了指定部分,便让他停下来,让另外一个线程执行,当另外一个线程执行到了指定部分后,
让这个线程停止执行,同时让停下来的线程继续执行,周而复始,直到结束
线程调用,目前我只能运用在两个线程并执行不同的函数,让结果符合我们的顺序
"""
cond = threading.Condition() #创建线程调用对象
def run1():
with cond:
for i in range(0,20,2):
print(threading.current_thread().name,i)
time.sleep(1)
cond.wait() #线程停止
cond.notify() #线程开始

def run2():
with cond:
for i in range(1,20,2):
print(threading.current_thread().name,i)
time.sleep(1)
cond.notify() #线程开始
cond.wait() #线程停止
# threading.Thread(target=run1).start()
# threading.Thread(target=run2).start()

"""
线程事件:
"""
# def func():
# event = threading.Event()
# def run():
# print("%s-开始" %(threading.current_thread().name))
# for i in range(5):
# event.wait()
# event.clear()
# print("执行次数:",i)
# print("%s-结束" %(threading.current_thread().name))
# t = threading.Thread(target=run).start()
# return event
#
# e = func()
# for i in range(5):
# time.sleep(2)
# e.set()

"""
线程间的通讯
生产者:生产数据,并将生产的数据给到队列
消费者:处理数据,从队列中取数据
"""
import queue
#生产者
def productor(int,queue):
while True:
num = random.randint(0,10000)
q.put(num)
print("%d生产线生产了的数据:%d放入了p队列" %(int,num))
time.sleep(2)
q.task_done() #任务完成

#消费者
def customer(int,queue):
while True:
item = q.get()
if item is None:
break
print("%d消费线消费了的数据:%d" %(int,item))
time.sleep(2)

# if __name__ == "__main__":
# #消息队列
# q =queue.Queue()
#
# for i in range(5):
# threading.Thread(target=productor,args=(1,q)).start()
#
# for i in range(5):
# threading.Thread(target=customer,args=(1,q)).start()

猜你喜欢

转载自www.cnblogs.com/hjlin/p/10663372.html