python treading模块

python threading模块

1.Thread类

1.1 构造器传参

Thread(group=None, target=None, name=None, args=(), kwargs={}, daemon=None)
  • group:指定的线程组ThreadGroup
  • target:捆绑的方法,是run()方法要调用的可调用对象。
  • name:线程名称,默认名为 Thread- N (N=1,2,3…)
  • args :给捆绑的方法(target)传递的参数元组
  • kwargs :给捆绑的方法(target)传递的参数字典
  • daemon : 显式设置线程是否为守护进程

1.2方法

start()

作用开启线程活动,激活线程后,线程对象将执行run()方法体中的操作。

def test(name):
    for i in range(5):
        print(name+'\t'+'hello',i)

#创建线程并捆绑一个函数来执行线程
thread01 = Thread(target=test, kwargs={'name':'thread01'})
thread01.start()

run()

代表线程活动的方法。

#类继承的方式重新run
class mytread(Thread):
    def __init__(self):
        super(mytread, self).__init__()
    #重新Thread的run方法
    def run(self):
        for i in range(5):
            print(self.getName()+'\t'+'hello',i)
thread1 = mytread()
thread1.start()

join(timeout=None)

阻塞当前运行代码的线程(也就是调用 join的线程),直到被调用 join()的线程终结 。

如下列中:

  • 主线程调用了thread1线程的join方法,当前运行线程为主线程。
  • 调用者:主线程(因为代码thread1.join()是在主线程中执行的,所有是主线程的调用thread1的join()方法)
  • 被调用者:thread1(thread1线程对象被在主线程中调用了join方法)
  • 结果:阻塞主线程,并直到thread1线程执行完成。
#创建线程tread1
...
#创建线程tread2
...
# 开启新线程
thread1.start()
thread2.start()

#主线程调用thread1的join方法,调用者:主线程,被调用者:thread1
#阻塞主线程,直到thread1执行完毕
thread1.join()  
#主线程调用thread2的join方法,调用者:主线程,被调用:thread2
#阻塞主线程,直到thread2执行完毕
thread2.join()
print ("退出主线程")

getName()

获取线程名,线程名:只用于识别的字符串。它没有语义。多个线程可以赋予相同的名称。 初始名称由构造函数设置。

setName()

设置线程名。

is_alive()

线程是否还在执行run()中的操作,用来判断线程是否存活。

isDaemon()

判断是否为守护线程

setDaemon()

设为守护线程。

1.3 使用

继承Thread,重新run方法

#类继承的方式重新run
class mytread(Thread):
    def __init__(self):
        super(mytread, self).__init__()
    #重新Thread的run方法
    def run(self):
        for i in range(5):
            print(self.getName()+'\t'+'hello',i)
thread1 = mytread()
thread1.start()
#阻塞当前线程,等待thread1的执行完毕
thread1.join()
print('主线程退出')

创建Thread,捆绑方法体执行

def test(name):
    #在这编写方法体
    for i in range(5):
        print(name+'\t'+'hello',i)

#创建线程并捆绑一个函数来执行线程
thread01 = Thread(target=test, kwargs={'name':'thread01'})
thread01.start()

2. Event类

这是线程之间通信的最简单机制之一:一个线程发出事件信号,而其他线程等待该信号。而Event就是用来实现事件对象的类。事件对象管理一个内部标志flag。而这个flag代表了事件信号。

一个线程发出事件信号,而其他线程等待该信号。可以说成:一个线程控制flag,而其他线程等待该flag变为true,然后去执行某件事。

2.1 方法

is_set()

当内部标准位flag为ture时返回true,否则返回false。

set()

设置内部标志位flag为true。所有正在等待这个事件的线程将被唤醒。当标志为true时,调用 wait() 方法的线程不会被被阻塞。

clear()

设置内部标志位flag为false。之后调用 wait() 方法的线程将会被阻塞,直到调用 set() 方法将内部标志再次设置为true。

wait(timeout=None)

阻塞线程,直到内部变量为true。

只有内部变量flag为true(不再进行阻塞),并没有超时,才会返回true。其余情况该方法返回的是false值。

posted @   鸭梨的药丸哥  阅读(15)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示