Python threading模块线程例子

目录

 

1.问题

2.线程使用模块

3.threading模块使用例子


1.问题

python如何使用线程

2.线程使用模块

python 线程模块早期的是使用thread的模块,python 2.0 之后开始使用threading模块。主要原因有两点。

第一、thread模块的主线程结束时不会等待子线程的结束,所有的子线程在主线程退出后强制退出。

第二、thread模块的线程锁只有一种。

threading模块改变了这些情况。目前来说主要使用的都是threading模块,有的需要涉及到底层数据结构的会使用到早期的thread模块

3.threading模块使用例子

import threading
from time import sleep,ctime

def loop(nloop,nsecs):
    print('nloop ',nloop,' start at:',ctime())
    sleep(nsecs)
    print('nloop ',nloop,' done at:',ctime())

loops=[4,2]
def main():
    print('loops start at:',ctime())
    nloops=range(len(loops))
    threads=[]
    for i in nloops:
        t=threading.Thread(target=loop,args=(i,loops[i]))
        threads.append(t)#保持线程对象
    for i in nloops:
        threads[i].start()#执行线程操作
    for i in nloops:
        threads[i].join()#等待子线程结束
    print('all loops done at:',ctime())

if __name__=='__main__':
    main()

threading模块很多时候都是继承thread类来写,代码如下

import threading
from time import sleep,ctime

def loop(nloop,nsecs):
	print('nloop ',nloop,' start at:',ctime())
    sleep(nsecs)
    print('nloop ',nloop,' done at:',ctime())

loops=[4,2]

class MyThread(threading.Thread):#继承线程类来操作
    def __init__(self,func,args,name=''):
        threading.Thread.__init__(self)
        self.func=func
        self.args=args
        self.name=name
    def run(self):
        self.func(*self.args)#调用函数
    def loop(nloop,nsec):#线程执行的内容
        print('start loop',nloop,' at:',ctime())
        sleep(nsec)
        print('loop',nloop,' done at:',ctime())
def main():
	print('starting at:',ctime())
    threads=[]
    nloops=range(len(loops))
    for i in nloops:
        t=MyThread(loop,(i,loops[i]),loop.__name__)
        threads.append(t)
    for i in nloops:
        threads[i].start()
    for i in nloops:
        threads[i].join()
    print('all Done at:',ctime())

if __name__=='__main__':
	main()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值