一、目的
这一节我们学习如何使用我们的ESP32开发板来进行多线程的学习。
二、环境
ESP32 + Thonny IDE
三、单任务
我们先来看看单任务单线程,从上到下依次执行,先是每隔1秒打印1个1,然后是每隔1秒打印1个2
- import time
-
-
- for i in range(3):
- print("1")
- time.sleep(1)
-
- for i in range(3):
- print("2")
- time.sleep(1)
输出为

四、多任务
我们再来看看多任务,多任务感觉上去程序可以同时执行多个不同的代码,例如多个while循环同时执行。
- import _thread
- import time
- import sys
- import machine
-
-
- def test1(*args, **kwargs):
- for i in range(3):
- print("1")
- time.sleep(1)
-
-
- def test2(*args, **kwargs):
- for i in range(3):
- print("2")
- time.sleep(1)
-
- # 此处创建2个线程
- thread_1 = _thread.start_new_thread(test1, (1,))
- thread_2 = _thread.start_new_thread(test2, (2,))
说明:_thread.start_new_thread
输出为:

五、MicroPython中的多线程
我们可以使用_thread来在ESP32中开发多进程的代码。如下:
- import _thread
- import time
- import sys
- import machine
-
-
- # ---------- 这是一个线程要执行的代码 ------------
- def test1(*args, **kwargs):
- while True:
- print("1")
- time.sleep(1)
-
-
- # ---------- 这是另一个线程要执行的代码 ------------
- def test2(*args, **kwargs):
- while True:
- print("2")
- time.sleep(1)
-
-
- # ---------- 这里创建线程 ------------
- thread_1 = _thread.start_new_thread(test1, (1,))
- thread_2 = _thread.start_new_thread(test2, (2,))
-
-
- # ---------- 这是主线程要执行的代码 ------------
- while True:
- print("3")
- time.sleep(1)
运行结果:

六、建议
在ESP开发板中,如果不是必须不建议使用多线程,因为我们的开关板存储和执行性能有限,多线程会带来大的开销,所以开发过程中我们要合理的安排。