首页 技术 正文
技术 2022年11月9日
0 收藏 671 点赞 4,200 浏览 1876 个字

python 多线程实现循环打印 abc

好久没写过python了, 想自己实践一下把

非阻塞版

import threading
import timedef print_a():
global value
global lock
global stop_flag
while stop_flag:
while True:
if value == 0 or value == 3:
break
lock.acquire()
value = 1
time.sleep(1)
print("aaa")
lock.release() def print_b():
global value
global lock
global stop_flag
while stop_flag:
while True:
if value == 1:
break
lock.acquire()
value = 2
time.sleep(1)
print("bbb")
lock.release()def print_c():
global value
global lock
global stop_flag
while stop_flag:
while True:
if value == 2:
break
lock.acquire()
value = 3
time.sleep(1)
print("ccc")
lock.release()if __name__ == "__main__":
stop_flag = True
value = 0
threads = []
lock = threading.Lock()
thread_a = threading.Thread(target=print_a)
thread_b = threading.Thread(target=print_b)
thread_c = threading.Thread(target=print_c)
threads.append(thread_a)
threads.append(thread_b)
threads.append(thread_c) for thread in threads:
thread.start()
time.sleep(5)
stop_flag = False

阻塞版

import threading
import timedef print_a():
global value
global stop_flag
global lock
global con
while stop_flag:
try:
lock.acquire()
while value != 0 and value != 3:
con.wait()
time.sleep(1)
value = 1
print("aaa")
con.notify_all()
finally:
lock.release()def print_b():
global value
global stop_flag
global lock
global con
while stop_flag:
try:
lock.acquire()
while value != 1:
con.wait()
time.sleep(1)
value = 2
print("bbb")
con.notify_all()
finally:
lock.release()def print_c():
global value
global stop_flag
global lock
global con
while stop_flag:
try:
lock.acquire()
while value != 2:
con.wait()
time.sleep(1)
value = 3
print("ccc")
con.notify_all()
finally:
lock.release()if __name__ == "__main__":
stop_flag = True
value = 0
threads = []
# 注意这里使用的是条件变量
lock = threading.Lock()
con = threading.Condition(lock=lock)
thread_a = threading.Thread(target=print_a)
thread_b = threading.Thread(target=print_b)
thread_c = threading.Thread(target=print_c)
threads.append(thread_a)
threads.append(thread_b)
threads.append(thread_c) for thread in threads:
thread.start()
time.sleep(5)
print("stop")
stop_flag = False
for thread in threads:
thread.join()
下一篇: bzoj4321
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,020
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,513
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,359
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,142
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,773
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,851