美文网首页
threading模块

threading模块

作者: NiceBlueChai | 来源:发表于2018-09-23 14:22 被阅读10次

threading模块不仅提供Thread类,还提供了各种非常好用的同步机制
_thread模块不支持守护线程,当主线程退出时所有子线程无论是否在工作,都会被强制退出。
threading模块支持守护线程,守护线程一般是一个等待客户请求的服务器,如果没有客户提出请求就一直等着。如果设定一个线程为守护线程,就表示这个线程不重要,在进程退出时不用等待这个线程退出。如果主线程退出时不用等待子线程完,就要设定这些线程的daemon属性,即在线程Thread.start()开始前,调用setDeamon()函数设定线程的daemon标志(Thread.setDaemon(True)),表示这个线程“不重要”。如果一定要等待子线程执行完成再退出主线程,就什么都不用做或显式调用Thread.setDaemon(False)以保证daemon标志为False,可以调用Thread.isDeamon()函数判断daemon标志的值。新的子线程会继承父线程的daemon标志,整个Python在所有非守护线程退出后才会结束。

threading的Thread类

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

import threading
from time import sleep
from datetime import datetime

loops=[4,2]
date_time_format="%y-%M-%d %H:%M:%S"

def date_time_str(date_time):
    return datetime.strftime(date_time,date_time_format)

def loop(n_loop,n_sec):
    print('线程(',n_loop,')开始执行:',date_time_str(datetime.now()),',先休眠(',n_sec,')秒')
    sleep(n_sec)
    print('线程(',n_loop,')休眠结束,结束于:',date_time_str(datetime.now()))
    

def main():
    print('---所有线程开始执行……',date_time_str(datetime.now()))
    threads=[]
    n_loops=range(len(loops))

    for i in n_loops:
        t=threading.Thread(target=loop,args=(i,loops[i]))
        threads.append(t)

    for i in n_loops:   #start threads
        threads[i].start()

    for i in n_loops:   #wait for all
        threads[i].join()   #threads to finish

    print('———所有线程执行结束:',date_time_str(datetime.now()))

if __name__=='__main__':
    main()

执行结果:

---所有线程开始执行…… 17-01-04 20:01:05
线程(0)开始执行: 17-01-04 20:01:05 ,先休眠(4)秒
 线程(1)开始执行:  17-01-04 20:01:05  ,先休眠(2)秒
线程( 1 )休眠结束,结束于: 17-01-04 20:01:07
线程( 0 )休眠结束,结束于: 17-01-04 20:01:09
———所有线程执行结束: 17-01-04 20:01:09

创建一个Thread的实例,并传给它一个可调用的类对象:

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

import threading
from time import sleep
from datetime import datetime

loops=[4,2]
date_time_format="%y-%M-%d %H:%M:%S"

class ThreadFunc(object):
    def __init__(self,func,args,name=''):
        self.name=name
        self.func=func
        self.args=args

    def __call__(self):
        self.func(*self.args)

def date_time_str(date_time):
    return datetime.strftime(date_time,date_time_format)

def loop(n_loop,n_sec):
    print('线程(',n_loop,')开始执行:',
          date_time_str(datetime.now()),',先休眠(',n_sec,')秒')
    sleep(n_sec)
    print('线程(',n_loop,')休眠结束,结束于:',
          date_time_str(datetime.now()))
    

def main():
    print('---所有线程开始执行……',date_time_str(datetime.now()))
    threads=[]
    n_loops=range(len(loops))

    for i in n_loops:   #create all threads
        t=threading.Thread(
            target=ThreadFunc(loop,(i,loops[i]),loop.__name__))
        threads.append(t)

    for i in n_loops:   #start threads
        threads[i].start()

    for i in n_loops:   #wait for completion
        threads[i].join()   

    print('———所有线程执行结束:',date_time_str(datetime.now()))

if __name__=='__main__':
    main()

相关文章

  • python --threading模块

    python3内置两个thread模块: _thread模块 threading模块推荐使用threading模块...

  • 线程

    多线程--threading python的thread模块是比较底层的模块,python的threading模块...

  • 多线程Threading介绍

    【threading模块详解】 模块基本方法 该模块定了的方法如下:threading.active_count(...

  • 1.6.1 Python线程使用 -- threading

    多线程-threading python的thread模块是比较底层的模块,python的threading模块是...

  • 线程实战

    多线程-threading python的thread模块是比较底层的模块,python的threading模块是...

  • Python多线程

    两个模块: _thread和threading,_thread是低级模块,threading是高级模块,对_thr...

  • 并发编程:线程,GIL全局解释器锁等

    线程 一 threading模块介绍 multiprocess模块的完全模仿了threading模块的接口,二者在...

  • 06.系统编程-2.线程

    1、多线程-threading python的thread模块是比较底层的模块,python的threading模...

  • 多线程

    threading 模块 在 Python 中实现多线程,可以利用 threading 模块中的 Thread 来...

  • 线程 threading

    1. 多线程-threading python的thread模块是比较底层的模块,python的threading...

网友评论

      本文标题:threading模块

      本文链接:https://www.haomeiwen.com/subject/qjcqmxtx.html