MicroPython 标准库和微型库 - _thread

MicroPython 标准库和微型库 - _thread

MicroPython 提供 Python 标准库功能的内置模块(例如 os、time)以及 MicroPython 特定的模块(例如 bluetooth, machine)。大多数标准库模块实现了等效 Python 模块的一部分功能,并且在少数情况下提供了一些 MicroPython 特定的扩展(例如 array, os)。

由于资源限制或其他限制,某些固件版本可能不包括官方手册的所有功能。可以通过在 REPL (Read-Eval-Print-Loop) 中输入以下命令来列出该固件版本所有的内置模块:

help('modules')

在这里插入图片描述
图 1. micropython_camera 固件中的内建模组

以下标准 Python 库已经过“微化”以适应 MicroPython 的理念。 它们提供该模块的核心功能,旨在成为标准 Python 库的直接替代品。

  • array – 数字数据的数组
  • binascii – 二进制/ASCII 转换
  • builtins – 内置函数和异常
  • cmath – 复数的数学函数
  • collections – 集合和容器类型
  • errno – 系统错误代码
  • gc – 控制垃圾收集器
  • hashlib – 散列算法
  • heapq – 堆队列算法
  • io – 输入/输出流
  • json – JSON 编码和解码
  • math – 数学函数
  • os – 基本的“操作系统”服务
  • random – 生成随机数
  • re – 简单的正则表达式
  • select – 等待一组流上的事件
  • socket – 网络插座模块
  • ssl – SSL/TLS 模块
  • struct – 打包和解包原始数据类型
  • sys – 系统特定的功能
  • time – 时间相关函数
  • uasyncio — 异步 I/O 调度程序
  • zlib – zlib 解压
  • _thread – 多线程支持

原则上,标准模块都实现了相应 CPython 模块的一个子集,有关更多信息,可以参阅原始 CPython 文档。CPython 是 Python 编程语言的参考实现,也是最著名的一种。然而,它是众多实现中的一种(包括 Jython、IronPython、PyPy 和 MicroPython)。虽然 MicroPython 的实现与 CPython 有很大不同,但它旨在尽可能保持兼容性。

_thread – 多线程支持

本模块提供了用于处理多个线程(也称为轻量级进程或任务)的函数。为 了同步,提供了简单的锁(也称为互斥锁或二进制信号量)。发生线程特定错误时,会RuntimeError引发异常。

以下示例会生成两个线程,第一个线程隔一秒印出一段信息,第二个线程隔二秒印出一段信息,分别重复 5 次后就结束。

参考代码

import _thread
import time

def th_func(delay, id):
    count = 5
    while count>0:
        time.sleep(delay)
        print( 'Running thread %d, time is %s' % (id, time.time()) )
        count -= 1
    print('\nThread %d is completed' % id)

for i in range(2):
    _thread.start_new_thread(th_func, (i + 1, i))

输出结果为:

Running thread 0, time is 731062810
Running thread 0, time is 731062811
Running thread 1, time is 731062811
Running thread 0, time is 731062812
Running thread 1, time is 731062813
Running thread 0, time is 731062813
Running thread 0, time is 731062814

Thread 0 is completed
Running thread 1, time is 731062815
Running thread 1, time is 731062817
Running thread 1, time is 731062819

Thread 1 is completed

_thread.start_new_thread(function,args [,kwargs])
启动一个新线程并返回其标识符。线程使用参数列表 args(必须是元组)执行函数。可选 kwargs 参数指定关键字参数的字典。 当函数返回时,线程将以静默方式退出。当函数以未处理的异常终止时,将打印堆栈跟踪,然后线程退出(但其他线程继续运行)。

_thread.exit()
引发 SystemExit 异常。如果未捕获时,这将导致线程以静默方式退出。

_thread.allocate_lock()
返回一个新的锁定对象。Python 提供的线程模块包含一个易于实现的锁定机制,可以实现线程之间的同步。通过调用 allocate_lock() 方法创建一个新锁。 新锁对象的获取(阻塞)方法用于强制线程同步运行。

lock.acquire(waitflag = 1,timeout = -1)
在没有任何可选参数的情况下,此方法无条件地获取锁定,如果有必要,等待它被另一个线程释放(一次只有一个线程可以获取锁定 - 这就是它们存在的原因)。如果存在整数 waitflag 参数,则操作取决于其值:如果它为零,则仅在不等待的情况下立即获取锁定时获取锁定,而如果它非零,则如上所述无条件地获取锁定。如果浮点超时参数存在且为正,则它指定返回之前的最长等待时间(以秒为单位)。负超时参数指定无限制等待。如果 waitflag 为零,则无法指定超时。True 如果成功获取锁定则返回值,否则返回值 False 。

lock.release()
释放锁定。必须先获取锁,但不一定是同一个线程。

lock.locked()
返回锁的状态:True 表示被某个线程获取,False 则表示没有。

以下示例是一个标准的生产者与消费者的多线程代码,透过锁定机制来确保消费时不会遇到无项目可消费的情形。
参考代码

import _thread
import time
items = []
# 生产者线程
def producer(id):
    global items
    time.sleep_ms(50)
    threadLock.acquire()
    items.append(id)
    print('producer thread {0} is completed, sum = {1}, , time is {2}'.format(id, items, time.time()))
    threadLock.release()
# 消费者线程
def consumer(id):
    global items
    # 检查是否有物品可以进行消费,若无则等待
    while len(items)==0:
        print('sleep')
        time.sleep_ms(10)
    threadLock.acquire()
    try:
        time.sleep_ms(5)
        items.pop()
    except Exception as e:
        print("error message", e)
    print('Consumer thread {0} is completed, sum = {1}, , time is {2}'.format(id, items, time.time()))
    threadLock.release()
# 取得锁
threadLock = _thread.allocate_lock()
for i in range(5):
    _thread.start_new_thread(producer, (i,))
    _thread.start_new_thread(consumer, (i,))

参考资料

  • mPython help documentation, https://mpython.readthedocs.io/en/master/index.html
  • MicroPython 文档, http://micropython.86x.net/en/latet/index-2.html
  • MicroPython documentation, https://docs.micropython.org/en/latest/index.html
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值