-
福利一海量deepseek资料包(持续更新)
-
福利二ComfyUI工作流&模型&插件
-
福利三AI工具集合包以及AI绘画解决方案
感觉上去程序可以同时执行多个不同的代码,例如多个while循环同时执行
看下面代码,猜猜结果是什么?
import time
for i in range(3):
print("1")
time.sleep(1)
for i in range(3):
print("2")
time.sleep(1)
# 请问会输出什么?
上述代码的输出结果如下:
1
1
1
2
2
2
再猜猜下面的代码运行的结果是什么?
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)
thread_1 = _thread.start_new_thread(test1, (1,))
thread_2 = _thread.start_new_thread(test2, (2,))
# 请问会输出什么?
运如结果下:
简单理解就是程序在执行的时候 一个可以执行代码的东西,你的程序默认只有1个(我们称为主线程),如果你额外创建了多个,那么其余的就叫做子线程
所以,要想实现多任务(就是同一时间有多个不同的代码同时执行),那么就创建线程就行了
就好比,你(主线程)可以干活,如果想同时可以干很多份活,就找多个人(这些人就是子线程)
有什么不好的地方呢?
答:你猜猜看,你请了很多人来帮你干活 他们需要什么呢?是不是需要工钱等,同理一个程序中如果创建了多个线程,那么代价就是需要更多的内存空间,如果内存不够那肯定不行的
再者ESP32的资源不是特别的充足(不像电脑动不动就16G、32G内存),因此千万不要创建没用的线程,合理安排规划程序是一个高级程序员的必备技能
MicroPython中可以用_thread模块,它有基本的常见线程等功能
看看下面的demo,相信就会用了
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)
说明:_thread.start_new_thread
我们可以使用_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)