haas506 2.0开发教程 - _thread - 多线程
- 开启关闭线程
- (1)案例说明
- (2)案例代码
- (3)输出log
- class - _thread
- get_ident - 获取当前线程ID
- stack_size - 设置创建新线程时所使用的栈大小
- start_new_thread - 创建一个新线程
- exit - 结束线程
- allocate_lock - 创建一个互斥锁对象
开启关闭线程
(1)案例说明
- _thread 模块提供创建新线程的方法,并提供互斥锁。
- 案例演示如何创建并关闭线程
(2)案例代码
import utime as time
import _thread
def th():
for i in range (5):
print('--- new_thread ---')
time.sleep_ms(1000)
#循环结束
print('_thread.exit')
_thread.exit()
if __name__ == '__main__':
_thread.start_new_thread(th, ()) #开启gps线程
while True:
print('=== main ===')
time.sleep_ms(1000)
(3)输出log
- 线程开启5秒后关闭
class - _thread
get_ident |
stack_size |
start_new_thread |
exit |
allocate_lock |
获取当前线程ID |
设置创建新线程时所使用的栈大小 |
创建一个新线程 |
结束线程 |
创建一个互斥锁对象 |
get_ident - 获取当前线程ID
函数原型:
- _thread.get_ident()
返回值:
- 获取当前线程号。
stack_size - 设置创建新线程时所使用的栈大小
函数原型:
- _thread.stack_size(size)
参数说明:
参数 |
类型 |
必选参数? |
说明 |
size |
int |
是 |
创建新线程使用的栈大小(以字节为单位),默认为8448字节,最小8192字节。 |
start_new_thread - 创建一个新线程
函数原型:
- _thread.start_new_thread(function, args)
参数说明:
参数 |
类型 |
必选参数? |
说明 |
function |
函数指针 |
是 |
新线程的入口函数 |
args |
元组 |
是 |
传入新线程的入口函数的参数列表 |
返回值:
- 返回线程的id。
exit - 结束线程
函数原型:
- _thread.exit ()
allocate_lock - 创建一个互斥锁对象
函数原型:
- _thread.allocate_lock()
返回值:
- 返回互斥锁对象