Python 多线程库总结

多线程库总结

基于线程的并行性

threading模块

下面是一些基础函数,函数包括:

函数
threading.active_count()
threading.current_thread()
threading.get_ident()
threading.enumerate()
threading.main_thread()
threading.settrace(func)
threading.setprofile(func)
threading.stack_size([size])
threading.TIMEOUT_MAX

threading模块一共提供的类包括:local、Thread、Lock、RLock、Condition、Semaphore、Event、Time

1. Thead-Local Data

专门用来管理线程局部的数据,也就是说一个线程会对应一个local,当前线程无法访问其它线程的局部数据,线程设置的属性也不会被其它线程同名的属性给替换掉。

函数
threading.local

例子如下:

import threading
class MyThread1(threading.Thread):
    def run(self):
        local = threading.local()
        if 'name' not in local.__dict__:
            print('thread1 not set name')
        local.name = 'li'
        print('thread1 {}'.format(local.name))
class MyThread2(threading.Thread):
    def run(self):
        local = threading.local()
        if 'name' not in local.__dict__:
            print('thread2 not set name')
        local.name = 'wang'
        print('thread2 {}'.format(local.name))
def main():
    print("Start main threading")
    local = threading.local()
    local.name = 'main'
    threads = [MyThread1(), MyThread2()]
    for t in threads:
        t.start()
    # 一次让新创建的线程执行 join
    for t in threads:
        t.join()
    print('main {}'.format(local.name))
if __name__ == '__main__':
    main()

其最后的输出结果为:

Start main threadingthread1 not set namethread1 lithread2 not set namethread2 wangmain main

2. Thread Obects

函数
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)
start()
run()
join(timeout=None)
name
getName()/setName()
ident
is_alive()
daemon
isDaemon()/setDaemon()

线程的创建有两种实现方式,分别是1.通过将一个可调用对象传递到构造函数中;2.通过继承Thread,在子类中重写run方法。Thread类定义为:

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)
# group应为None;保留用于在实现ThreadGroup类时的未来扩展。
# target是将被run()方法调用的可调用对象。默认为None,表示不调用任何东西。
# name是线程的名字。默认情况下,以“Thread-N”的形式构造一个唯一的名字,N是一个小的十进制整数。
# args是给调用目标的参数元组。默认为()。
# kwargs是给调用目标的关键字参数的一个字典。默认为{}。
# 如果daemon不是None,守护程序显式设置线程是否为daemonic。如果为None(默认值),daemonic属性从当前线程继承。

注意:应该始终以关键字参数调用该构造函数。

3. Lock Objects

为了保证数据的准确性,引入了锁的概念,原锁是一个同步原语,是当前可用的最低级同步原语。

函数
class threading.Lock
acquire(blocking=True, timeout=-1)
release()

4. RLock Objects

和Lock的区别在于RLock允许在同一线程中被多次acquire,但是Lock却不允许这种情况,使用acquire的次数需要和release的次数相互对应;

函数
class threading.Lock
acquire(blocking=True, timeout=-1)
release()

5. Condition Objects

条件变量总是与某种锁相关联

函数
class threading.Condition(lock=None)
acquire(*args)
release()
wait(timeout=None)
wait_for(predicate, timeout=None)
notify(n=1)
notify_all()

6. Semaphore Objects

信号量管理内部计数器,每个acquire()调用递减,每个release()调用递增。计数器永远不会低于零;当acquire()发现它为零时,它阻塞,等待其他线程调用release()。

函数
class threading.Semaphore(value=1)
class threading.BoundedSemaphore(value=1)
acquire(blocking=True, timeout=None)
release()

7. Event Objects

事件对象是线程间最简单的通信机制之一:线程可以激活在一个事件对象上等待的其他线程。每个事件对象管理一个内部标志,可以在事件对象上调用set() 方法将内部标志设为true,调用 clear() 方法将内部标志重置为false。wait()方法将阻塞直至该标志为真。

函数
class threading.Event
is_set()
set()
clear()
wait(timeout=None)

8. Timer Objects

这个类表示一个动作应该在一个特定的时间之后运行 — 也就是一个计时器。Timer是Thread的子类, 因此也可以使用函数创建自定义线程

函数
class threading.Timer(interval, function, args=None, kwargs=None)
cancel()

9. Barrier Objects

这个类提供了一个简单的同步原语,供需要彼此等待的固定数量的线程使用。每个线程尝试通过调用wait()方法传递屏障,并将阻塞,直到所有线程都调用。

函数和属性
class threading.Barrier(parties, action=None, timeout=None)
wait(timeout=None)
reset()
abort()
parties
n_waiting
broken
exception threading.BrokenBarrierError

参考线程总结

项目:

  1. 实现一
  2. 实现二
原文地址:https://www.cnblogs.com/George1994/p/7512633.html