要在Python进行多线程只需要简单地导入threading
import threading |
import threading from time import sleep works = [1,2,3,4,5,6,7] lock = threading.Lock() def func(work): sleep(1) print(work) sleep(5) class workerThread(threading.Thread): def __init__(self, thread_name, lock, works, daemon=True): threading.Thread.__init__(self) self.daemon = daemon self.name = thread_name self.lock = lock self.works = works def run(self): while len(works) > 0: self.lock.acquire() work = works.pop() self.lock.release() func(work) |
线程对象为 threading.Thread 的子类,通过重写run() 实现执行值得代码。
锁(lock)对象为 thrading.Lock() 对象,带有acquire(), release()两个方法,用于实现线程同步。
线程对象属性 daemon,定义是否为守护线程。
daemon = True 时,主线程结束,子线程一并结束。
daemon = False 时,主线程结束时会被未结束的子线程阻塞。
此属性可使用 setDaemon(True|False) 进行变更。