threading模块函数

时间:2021-08-04
本文章向大家介绍threading模块函数,主要包括threading模块函数使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.threading.active_count():返回当前存活的threading.Thread线程对象数量,等同于len(threading.enumerate())。

import threading
print(threading.active_count())
print(len(threading.enumerate()))

输出:

1
1

2.threading.get_ident():返回当前线程的线程标识符。注意当一个线程退出时,它的线程标识符可能会被之后新创建的线程复用。

import threading
print(threading.current_thread())
print(threading.get_ident())

输出:

<_MainThread(MainThread, started 26816)>
26816

3.threading.enumerate():返回当前存活的threading.Thread线程对象列表。

import threading
print(threading.enumerate())

输出:

[<_MainThread(MainThread, started 25328)>]

4.threading.Event()

事件处理的机制:全局定义了一个“Flag”,如果“Flag”值为 False,那么当程序执行 event.wait 方法时就会阻塞;如果“Flag”值为True,那么执行event.wait 方法时便不再阻塞。

clear:将“Flag”设置为False
set:将“Flag”设置为True
用 threading.Event 实现线程间通信,使用threading.Event可以使一个线程等待其他线程的通知,我们把这个Event传递到线程对象中,

Event默认内置了一个标志,初始值为False。一旦该线程通过wait()方法进入等待状态,直到另一个线程调用该Event的set()方法将内置标志设置为True时,该Event会通知所有等待状态的线程恢复运行。

通过Event来实现两个或多个线程间的交互,下面是一个红绿灯的例子,即起动一个线程做交通指挥灯,生成几个线程做车辆,车辆行驶按红灯停,绿灯行的规则。

import threading,time,random

def light():
    if not event.is_set():
        event.set()
    n = 0
    while True:
        if n < 10:
            print('此时是绿灯,可以通行!')
        elif n < 13:
            print('此时是黄灯,请减速!')
        elif n < 20:
            print('此时是红灯,禁止通行!!!')
            event.clear() # 此时的flage为Flase
        else:
            n = 0
            event.set()  # 打开绿灯,此时的Flage为True
        time.sleep(1)
        n += 1
def car(c):
    time.sleep(random.randrange(3, 10))
    while True:
        if event.is_set():
            print('%s 正在通过' % c)
        else:
            print('%s 正在的等红灯' % c)
            event.wait()


if __name__ == '__main__':
    event = threading.Event()
    c = ['BMW', 'AUDI', 'Benz']
    light = threading.Thread(target=light)
    light.start()
    for i in c:
        t = threading.Thread(target=car, args=(i,))
        t.start()

5. thread.join(timeout=None)

会阻塞调用这个方法的线程,直到被调用 join() 的线程终结 -- 不管是正常终结还是抛出未处理异常 -- 或者直到发生超时,超时选项是可选的。

当 timeout 参数存在而且不是 None 时,它应该是一个用于指定操作超时的以秒为单位的浮点数或者分数。

因为 join() 总是返回 None ,所以你一定要在 join() 后调用 is_alive() 才能判断是否发生超时 -- 如果线程仍然存活,则 join() 超时。

当 timeout 参数不存在或者是 None ,这个操作会阻塞直到线程终结。

(1)未设置timeout

import threading, time


def test():
    n = 0
    while n < 10:
        print(n)
        n += 1
        time.sleep(1)


c = threading.Thread(target=test)
c.start()
c.join()
print(c.is_alive())
print('结束')

输出:

0
1
2
...
8
9
False
结束

(2)设置timeout

import threading, time


def test():
    n = 0
    while n < 10:
        print(n)
        n += 1
        time.sleep(1)


c = threading.Thread(target=test)
c.start()
c.join(timeout=5)
print(c.is_alive())
print('结束')

输出:

0
1
2
3
4
True
结束
5
6
7
8
9

6.thread.setDaemon()

设置守护线程,主线程结束后,子线程不管是否结束强制结束;

import threading,time
def ccc():
    n = 0
    while n < 10:
        print(n)
        n += 1
        time.sleep(1)

c = threading.Thread(target=ccc)

print(c.daemon)  # 查看状态
c.setDaemon(True)     # 设置守护线程
print(c.daemon)
c.start()
print('jieshu')

输出:

False
True
0jieshu

7.threading.Lock()

线程锁,如果多个线程共同对某个数据修改,则可能出现不可预料的结果,因为操作系统调用多线程的顺序是随机的,为了保证数据的正确性,需要加锁。

import threading

# 假如这是你的银行村矿
balance = 0
lock = threading.Lock()


def change_it(n):
    global balance
    balance = balance + n
    balance = balance - n


def run_thread(n):
    for i in range(100000):
        lock.acquire() #获取锁
        change_it(n)
        lock.release() #释放锁


t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)

8.threading.Condition()

可以把Condiftion理解为一把高级的琐,它提供了比Lock, RLock更高级的功能,允许我们能够控制复杂的线程同步问题。

(1)wait([timeout]):线程挂起,直到收到一个notify通知或者超时(可选的,浮点数,单位是秒s)才会被唤醒继续运行。

(2)notify(n=1):通知其他线程,那些挂起的线程接到这个通知之后会开始运行,默认是通知一个正等待该condition的线程,最多则唤醒n个等待的线程。notify()必须在已获得Lock前提下才能调用,否则会触发RuntimeError。notify()不会主动释放Lock。

(3)notifyAll(): 如果wait状态线程比较多,notifyAll的作用就是通知所有线程(这个一般用得少)

import threading,time

def Seeker(cond, name):
    time.sleep(2)
    cond.acquire()
    print('%s :我已经蒙上眼睛了!' % name)
    cond.notify()
    cond.wait()
    for i in range(3):
        print('%s is finding!!!' % name)
        time.sleep(2)
    cond.notify()
    cond.release()
    print('%s :我赢了!' % name)

def Hider(cond, name):
    cond.acquire()
    cond.wait()
    for i in range(3):
        print('%s is Hiding!!!' % name)
        time.sleep(2)
    print('%s :我已经藏好了,你快来找我吧!!!' % name)
    cond.notify()
    cond.wait()
    cond.release()
    print('%s :被你找到了,唉~^~!' % name)


if __name__ == '__main__':
    cond = threading.Condition()
    seeker = threading.Thread(target=Seeker,args=(cond,'seeker'))
    hider = threading.Thread(target=Hider,args=(cond,'Hider'))
    seeker.start()
    hider.start()

原文地址:https://www.cnblogs.com/landlord1127/p/15099050.html