Python线程模块
Python标准库中关于线程的主要是_thread和threading模块
①_thread模块
标准库中的_thread模块作为低级别的模块存在,一般不建议直接使用(从模块名字以“_”开头就可以看出官方并不希望我们直接使用),但在某些简单的场合也是可以使用的,因为_thread模块的使用方法十分简单。
标准库_thread模块的核心其实就是start_new_thread方法:
_thread.start_new_thread(function,args [,kwargs])
启动一个新线程并返回其标识符,线程使用参数列表args(必须是元组)执行函数,可选的kwargs参数指定关键字参数的字典。当函数返回时,线程将以静默方式退出。当函数以未处理的异常终止时,将打印堆栈跟踪,然后线程退出(但其他线程继续运行)。
01
02
03
04 import time
05 import datetime
06 import _thread
07
08 date_time_format="%H:%M:%S"
10 def get_time_str():
11 now=datetime.datetime.now()
12 return datetime.datetime.strftime (now,date_time_format)
13
14 def thread_function (thread_id):
15 print (“Thread %d\t start at %s” % (thread_id, get_time_str())
16 print(“Thread %d\ t sleeping” % thread_id)
17 time.sleep(4)
18
Python线程模块
最新推荐文章于 2023-07-10 14:10:10 发布