本帖最后由 ∫護着妳佉遠方 于 2022-1-31 15:41 编辑
Python多线程中,主线程等子线程退以后主线程才能退出
我写的这个为什么不能退出啊,运行完毕以后,不打印 "票卖完",一直在卡在哪里
求助,问题原因和解决办法
[Python] 纯文本查看 复制代码 """
* @codding : utf-8
* [url=home.php?mod=space&uid=238618]@Time[/url] : 2022/1/30 20:18:41
* [url=home.php?mod=space&uid=170990]@name[/url] : 卖票系统.py
* [url=home.php?mod=space&uid=153612]@system[/url] : Windows 11
* @Types : pythonProject
* [url=home.php?mod=space&uid=371834]@SOFTWARE[/url] : PyCharm
* [url=home.php?mod=space&uid=686208]@AuThor[/url] :
"""
import time
import threading
lock = threading.Lock()
g_num = 100
def one_thread(name):
while True:
# 上锁
lock.acquire()
global g_num
if g_num == 0:
break
else:
g_num -= 1
print('{}正在执行,当前还剩{}张票'.format(name, g_num))
# 执行完毕,释放锁
lock.release()
time.sleep(0.2)
if __name__ == '__main__':
thread1 = threading.Thread(target=one_thread, args={"线程一"})
thread2 = threading.Thread(target=one_thread, args={"线程二"})
thread3 = threading.Thread(target=one_thread, args={"线程三"})
thread1.start()
thread2.start()
thread3.start()
thread1.join()
thread2.join()
thread3.join()
print('票全部卖完')
|