Posted in Python onJune 17, 2020
一、线程创建方法
1. 普通创建
import 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() -------------------------------------------- t1 t2 t2 t1 t2 t1
2. 自定义线程类
import 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()
二、线程的使用
1.守护线程
子线程会随着主线程的结束而结束
t = threading.Thread(target=run, args=("t1",))
t.setDaemon(True) # 把子进程设置为守护线程,必须在start()之前设置
t.start()
2.主线程等待子线程结束
t = threading.Thread(target=run, args=("t1",))
t.setDaemon(True)
t.join() # 设置主线程等待子线程结束
t.start()
3.互斥锁
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创建及使用方法解析
- Author -
吞风吻雨ii声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@