提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
python 线程
case1: 普通方式创建, threading.Thread(target=run, args={XXX})
import threading
import time
# case1: using threading to create threads
def run(n):
print("task %s" % n)
time.sleep(1)
if __name__ == '__main__':
t1 = threading.Thread(target=run, args=("t1",))
t2 = threading.Thread(target=run, args=("t2",))
t1.start()
t2.start()
case2: 自定义线程,通过继承threading.Thread来自定义线程类,本质是重构Thread类中的run()
class MyThread(threading.Thread):
def __init__(self, n):
super(MyThread, self).__init__()
self.n = n
def run(self):
print("task", self.n)
time.sleep(1)
print("2s")
time.sleep(1)
print("1s")
if __name__ == "__main__":
t1 = MyThread("t1")
t2 = MyThread("t2")
t1.start()
t2.start()
代码如下(示例):
#!/usr/bin/env python3
import threading
import time
# 设置守护线程,
# t.setDaemon(True) 把所有的子线程变成主线程的守护线程,当主线程结束后,所有的子线程也会随之结束
# 进一步升级就是,为了让手下线程结束后主线程再结束,加上join(),让主线程等待子线程执行
def run(n):
print("Start thread", n)
time.sleep(1)
print('3')
time.sleep(1)
print('2')
time.sleep(1)
print('1')
print("End thread", n)
if __name__ == '__main__':
print("Start main thread")
t = threading.Thread(target=run, args=("t1",))
# 将子thread 设置成守护线程,必须在start之前设置
t.setDaemon(True)
t.start()
# 设置主线程等待子线程结束
t.join()
print("End main thread")
TODO: 线程,进程,资源调度的延伸
import threading
import time
g_num = 100
def work1():
global g_num
for i in range(3):
g_num += 1
print("in work1 g_num is : %d" % g_num)
def work2():
global g_num
print("in work2 g_num is : %d" % g_num)
if __name__ == '__main__':
t1 = threading.Thread(target=work1)
t1.start()
time.sleep(1)
t2 = threading.Thread(target=work2)
t2.start()
----------------------------------
>>> in work1 g_num is : 103
>>> in work2 g_num is : 103
TODO: 互斥锁的引入,远离,应用场景, 递归锁
from threading import Thread,Lock
import os,time
def work():
global n
lock.acquire()
temp=n
time.sleep(0.1)
n=temp-1
lock.release()
if __name__ == '__main__':
lock=Lock()
n=100
l=[]
for i in range(100):
p=Thread(target=work)
l.append(p)
p.start()
for p in l:
p.join()
参考:
https://www.liujiangblog.com/course/python/79
https://www.cnblogs.com/luyuze95/p/11289143.html