使用 threading 这个模块(就是一个文件)
重要的 class
Thead(和Java的基本一致)
- start
- run
使用Thread类的target属性时,实际上相当于将目标函数指定为线程的run方法
- join(timeout=None)
- 作用: 用来进行线程同步
- 参数
- timeout: 如果在 timeout这个时间内都没有执行join成功,就往下执行,不再等待同步
- is_alive
使用
start&join | import 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() | | | | | | 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}") | | | | time.sleep(1) | | | | | | | | thread1 = MyThread() | | thread2 = MyThread() | | | | | | thread1.start() | | thread2.start() | | | | | | thread1.join() | | thread2.join() | | | | print("Main thread continues...") |
Lock
使用
with&acquire_release | import threading | | | | my_lock = threading.Lock() | | | | with my_lock: | | print('类似 with open 的文件操作一样,这里的操作是原子性的') | | | | my_lock.acquire() | | print('通过 acquire 和 release 中间的操作也是原子性的') | | my_lock.release() |
Event
作用
使用
set/clear/wait | | | import 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.") | | | | | | | | 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(信号量)
作用
- 信号量是一种更为灵活的同步原语,它允许多个线程同时访问共享资源,但限制同时访问的线程数量。
|
|
|
23 |
24 |
25 |
26 |
27 |
28 |
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
9
|
10
|
11
|
12
|
13
|
14
|
15
|
16
|
17
|
18
|
19
|
20
|
21
|
22
|
23
|
24
|
25
|
26
|
27
|
28
|
29
|
30
|
31
|
1
|
2
|
3
|
4
|
5
|
|
|
|
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步