threading

demo

创建两个线程,分别执行函数 eyekeyboardterminal

1
2
3
4
5
6
7
8
# 监视键盘
keyboard_thread = threading.Thread(target=eyekeyboard,daemon=True)
keyboard_thread.start()


# 终端
terminal_thread = threading.Thread(target=terminal)
terminal_thread.start()

这里参数 daemon=True 意思是将这个线程设置为守护线程。守护线程会在主线程结束时自动结束。

线程间通信

使用 queue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import threading
import queue
import time

Q=queue.Queue()
def th1_fun():
while True:
time.sleep(1)
Q.put({"apple":1,"banana":2})


def th2_fun():
while True:
time.sleep(1)
(apple,banana)=Q.get().values()
print(apple,banana)
th1=threading.Thread(target=th1_fun)
th1.start()

th2=threading.Thread(target=th2_fun)
th2.start()

一个线程put,另一个线程get