收藏

micropython esp32 中的多线程

分类: 基础知识篇 >> Micropython基础知识 发布于 2024-05-16 357次阅读0点赞0收藏

什么是多任务

感觉上去程序可以同时执行多个不同的代码,例如多个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

  • 第1个参数,函数的引用,理解为线程要到哪里执行代码
  • 第2个参数,元组,要给线程执行函数的实参,必须是元组
  • 第3个参数(可有可无),命名参数,给线程执行函数的实参

我们可以使用_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)
VIP
购买
建议
意见
联系
客服
在线咨询

您可以与在线客服进行沟通获得帮助

工作日:8:00~22:00节假日:9:00~20:00

微信号: mpyos01

Q Q号: 1401211620

免费
福利
0.022327s