Python "多线程"
使用 threading 这个模块(就是一个文件)
重要的 class
Thead(和Java的基本一致)
- start
- run
使用Thread类的target属性时,实际上相当于将目标函数指定为线程的run方法 - join(timeout=None)
- 作用: 用来进行线程同步
- 参数
- timeout: 如果在 timeout这个时间内都没有执行join成功,就往下执行,不再等待同步
- is_alive
- 作用:判定线程是否活着
使用
start&joinimport threading def p_thread_runner(*args): i = 0 while args[0][0] is True: print(i) i += 1 if __name__ == '__main__': can_run = [True] p_thead = threading.Thread(target=p_thread_runner, args=(can_run,)) p_thead.start() # can_run[0] = False # 用来同步的 p_thead.join(timeout=0)run的重写import threading import time class MyThread(threading.Thread): def run(self) -> None: super().run() for i in range(5): print(f"Thread {self.name} is running - {i}") # 和 asyncio 里面的一样吗 time.sleep(1) # 创建两个线程实例 thread1 = MyThread() thread2 = MyThread() # 启动线程,实际上是调用了 run 方法 thread1.start() thread2.start() # 等待线程执行完成 thread1.join() thread2.join() print("Main thread continues...")
Lock
使用
with&acquire_releaseimport threading my_lock = threading.Lock() with my_lock: print('类似 with open 的文件操作一样,这里的操作是原子性的') my_lock.acquire() print('通过 acquire 和 release 中间的操作也是原子性的') my_lock.release()
Event
作用
- 类似一个sleep,你叫他sleep就sleep
使用
set/clear/waitimport threading import time def worker(event, thread_id): print(f"Thread {thread_id} is waiting for the event.") event.wait() # 等待事件触发 print(f"Thread {thread_id} received the event and continues.") # 创建 Event 实例 my_event = threading.Event() # 创建线程 thread1 = threading.Thread(target=worker, args=(my_event, 1)) thread2 = threading.Thread(target=worker, args=(my_event, 2)) # 启动线程 thread1.start() thread2.start() # 主线程等待一段时间 time.sleep(2) # 主线程触发事件 print("Main thread sets the event.") my_event.set() # 等待线程执行完成 thread1.join() thread2.join() print("Main thread continues.")
Condition
作用
- 用于实现线程间的协调和同步。Condition 类提供了一种更高级别的锁定机制
Semaphore(信号量)
作用
- 信号量是一种更为灵活的同步原语,它允许多个线程同时访问共享资源,但限制同时访问的线程数量。

浙公网安备 33010602011771号