首页 > 编程语言 > 详细

多线程模块:threading

时间:2019-02-07 18:16:42      阅读:220      评论:0      收藏:0      [点我收藏+]

threading 常见用法:

(1) 在 thread 中,我们是通过 thread.start_new_thread(function, args) 来开启一个线程,接收一个函数和该函数的参数,函数的参数必须是元组的形式
(2) 在 threading 中,我们是通过 threading.Thread(target=function, args=(....)) 来创建一个对象,然后再通过对象的 start() 方法来开启一个线程,多个线程可以并发执行

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import time
import threading

def fun():
    print time.ctime()
    time.sleep(1)

for i in range(3):
    t = threading.Thread(target=fun, args=())    # 创建一个 Thread 对象,接收一个函数和该函数的参数
    t.start()                                    # 通过对象来开启一个新的线程,通过线程来执行函数
[root@localhost ~]$ python 1.py    # 多个线程并发执行,只需要执行一秒
Mon Jan 28 21:15:35 2019
Mon Jan 28 21:15:35 2019
Mon Jan 28 21:15:35 2019


t.join()方法用于阻塞下一个线程的运行,等待当前线程执行完再执行下一个线程,例子如下:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import time
import threading

def fun():
    print time.ctime()
    time.sleep(1)

for i in range(3):
    t = threading.Thread(target=fun, args=())
    t.start()
    t.join()
[root@localhost ~]$ python 1.py     # 由于线程被阻塞,需要执行3秒
Mon Jan 28 21:33:35 2019
Mon Jan 28 21:33:36 2019
Mon Jan 28 21:33:37 2019


t.setDaemon()方法用于是否设置当前线程随着主线程的退出而退出,例子如下:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import time
import threading

def fun():                    # 函数的功能是打印三次当前时间
    for i in range(3):   
print time.ctime() time.sleep(1) t = threading.Thread(target=fun, args=()) t.setDaemon(True) t.start()

print ‘End...‘ # 执行 print 之后,主线程就退出了,最终结果只会打印一次
[root@localhost ~]$ python 1.py 
Mon Jan 28 21:54:48 2019
End...

 

 

 

 

 

 

    

 

多线程模块:threading

原文:https://www.cnblogs.com/pzk7788/p/10355006.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!