Python - 创建线程


_thread 模块中包含的 start_new_thread() 函数用于正在运行的程序中创建一个新线程。

句法

_thread.start_new_thread ( function, args[, kwargs] )

该函数启动一个新线程并返回其标识符。

参数

  • function - 新创建的线程开始运行并调用指定的函数。如果函数需要任何参数,则可以将其作为参数 args 和 kwargs 传递。

例子

import _thread
import time
# Define a function for the thread
def thread_task( threadName, delay):
   for count in range(1, 6):
      time.sleep(delay)
      print ("Thread name: {} Count: {}".format ( threadName, count ))

# Create two threads as follows
try:
   _thread.start_new_thread( thread_task, ("Thread-1", 2, ) )
   _thread.start_new_thread( thread_task, ("Thread-2", 4, ) )
except:
   print ("Error: unable to start thread")

while True:
   pass

它将产生以下输出-

Thread name: Thread-1 Count: 1
Thread name: Thread-2 Count: 1
Thread name: Thread-1 Count: 2
Thread name: Thread-1 Count: 3
Thread name: Thread-2 Count: 2
Thread name: Thread-1 Count: 4
Thread name: Thread-1 Count: 5
Thread name: Thread-2 Count: 3
Thread name: Thread-2 Count: 4
Thread name: Thread-2 Count: 5
Traceback (most recent call last):
 File "C:\Users\user\example.py", line 17, in <module>
  while True:
KeyboardInterrupt

程序陷入无限循环。您必须按“ctrl-c”才能停止。