文章目录
- 开启线程
- 守护线程 - 报活示例
- 高级用法
- 线程锁
- 线程队列 - queue - 处理数据加锁的问题
- 信号量 - semaphore
- 事件 - Event - 等待状态变更
- 计时器 - Timer
开启线程
方式1: 直接定义线程代码
from threading import Thread
def f(name): pass
if __name__ == "__main__":
t = Thread(target=f, args=("Tim",))
t.start()
写法2: 自定义类
from threading import Thread
class MyThread(Thread):
def run(self, name): pass
if __name__ == "__main__":
t = MyThread()
t.run("Tom")
守护线程 - 报活示例
""" 当主线程回收所有资源之后, 守护线程才会结束 """
from threading import Thread
import time
def task_d():
while 1:
print("still alive..")
time.sleep(0.5)
def task():
for i in range(5):
print("task %s" % i)
time.sleep(1)
if __name__ == "__main__":
t = Thread(target=task)
td = Thread(target=task_d)
td.daemon = True
t.start()
td.start()
t.join()
print("end main")
高级用法
线程锁
from threading import Thread, Lock
import time
n = 100
def task():
global n
with mutex:
tmp = n
time.sleep(0.1)
n = tmp-1
if __name__ == "__main__":
l = []
mutex = Lock()
for i in range(100):
t = Thread(target=task)
l.append(t)
t.start()
for i in l:
i.join()
print("main end", n)
线程队列 - queue - 处理数据加锁的问题
import queue
q = queue.Queue(3)
q.put(1)
q.put(2)
print(q.get())
q = queue.LifoQueue(3)
q.put(1)
q.put(2)
print(q.get())
q = queue.PriorityQueue(3)
q.put((10, 1))
q.put((100, True))
q.put((-10, "string"))
print(q.get())
信号量 - semaphore
from threading import Thread, Semaphore, current_thread
import time, random
sm = Semaphore(5)
def task():
with sm:
print("%s is laing" % current_thread().getName())
time.sleep(random.randint(1, 3))
if __name__ == "__main__":
for i in range(20):
t = Thread(target=task)
t.start()
事件 - Event - 等待状态变更
from threading import Thread, Event
import time
def check():
print("check mysql")
time.sleep(5)
e.set()
print("check complate")
def conn():
count = 1
while not e.is_set():
if count > 3:
raise TimeoutError("超时")
print("try to connect Mysql time %s" % count)
e.wait(2)
count += 1
print("connect complate")
if __name__ == "__main__":
e = Event()
print(e.isSet())
t1 = Thread(target=check)
t2 = Thread(target=conn, name="t2")
t3 = Thread(target=conn, name="t3")
t1.start()
t2.start()
t3.start()
e.clear()
计时器 - Timer
from threading import Timer
def hello(name):
print("hello world %s" % name)
t = Timer(1, hello, args=("Tim",))
t.start()