python 多线程threading的使用
2021-02-21 00:20
标签:16px name 主线程等待子线程 init 子线程 rom __name__ run join 一、线程创建方法 1. 普通创建 t1 2. 自定义线程类 二、线程的使用 1.守护线程 子线程会随着主线程的结束而结束 2.主线程等待子线程结束 3.互斥锁 python 多线程threading的使用 标签:16px name 主线程等待子线程 init 子线程 rom __name__ run join 原文地址:https://www.cnblogs.com/LMIx/p/12678351.htmlimport threading
def run(name):
for i in range(3):
print(name)
if __name__ == ‘__main__‘:
t1 = threading.Thread(target=run, args=("t1",))
t2 = threading.Thread(target=run, args=("t2",))
t1.start()
t2.start()
--------------------------------------------
t2
t2
t1
t2
t1import threading
class MyThread(threading.Thread):
def __init__(self, name):
super(MyThread, self).__init__()
self.name = name
def run(self):
for i in range(3):
print(self.name)
if __name__ == "__main__":
t1 = MyThread("t1")
t2 = MyThread("t2")
t1.start()
t2.start()
t = threading.Thread(target=run, args=("t1",))
t.setDaemon(True) # 把子进程设置为守护线程,必须在start()之前设置
t.start()
t = threading.Thread(target=run, args=("t1",))
t.setDaemon(True)
t.join() # 设置主线程等待子线程结束
t.start()
from threading import Thread,Lock
n = 10
def run():
global n
locker.acquire()
n -= 1
locker.release()
if __name__ == ‘__main__‘:
locker = Lock()
t1 = Thread(target=run)
t2 = Thread(target=run)
t1.start()
t2.start()
文章标题:python 多线程threading的使用
文章链接:http://soscw.com/index.php/essay/58218.html