VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • Python3基础之python使用多线程

threading 模块支持守护线程, 其工作方式是:守护线程一般是一个等待客户端请求服务的服务器。 

如果把一个线程设置为守护线程,进程退出时不需要等待这个线程执行完成。

如果主线程准备退出时,不需要等待某些子线程完成,就可以为这些子线程设置守护线程标记。 需要在启动线程之前执行如下赋值语句: thread.daemon = True,检查线程的守护状态也只需要检查这个值即可。

整个 Python 程序将在所有非守护线程退出之后才退出, 换句话说, 就是没有剩下存活的非守护线程时才退出。 

 

使用thread模块

以下是三种使用 Thread 类的方法(一般使用第一个或第三个方案)

  • 创建 Thread 的实例,传给它一个函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import threading
from time import sleep, ctime
loops = [32111]
def loop(i, nsec):
    print(f'start loop {i} at: {ctime()}')
    sleep(nsec)
    print(f'end loop {i} at: {ctime()}')
def main():
    print('start at', ctime())
    threads = []
    nloops = range(len(loops))
    for in nloops:
        = threading.Thread(target=loop, args=(i, loops[i]))
        threads.append(t)
    for in nloops: # start threads
        threads[i].start()
    for in nloops: # wait for all
        threads[i].join() # threads to finish
    print(f'all done at: {ctime()}')
if __name__ == '__main__':
    main()