multithreading

来源:互联网 发布:卡宾雪板 知乎 编辑:程序博客网 时间:2024/04/29 16:07

转自:
廖学峰大神

多线程

一个进程至少有一个线程。
线程是操作系统直接支持的执行单元,因此,高级语言都支持多线程。
python的多线程是真正的posix thread,并不是模拟出来的线程。
原来,在标准库中有多线程模块,_thread以及threading。其中,_thread是低级模块,threadind是其封装版,比较高级。
使用高级模块不易出错,并且比较方便。

import time, threadingdef loop():    print(" threading %s is running..." % (threading.current_thread().name))    n = 0    while n < 5:        n += 1        print("threading %s >>> %s" % (threading.current_thread().name, n))        time.sleep(2)    print('thread %s ended.' % (threading.current_thread().name))print(" threading %s is running..." % (threading.current_thread().name))t = threading.Thread(target=loop, name='loopThread')t.start()t.join()print('thread %s ended.' % (threading.current_thread().name)) threading MainThread is running... threading loopThread is running...threading loopThread >>> 1threading loopThread >>> 2threading loopThread >>> 3threading loopThread >>> 4threading loopThread >>> 5thread loopThread ended.thread MainThread ended.

进程中至少有一个线程。也就是说,线程的存在必须以进程的存在为先决条件。启动一个进程的时候,系统默认在该进程下启动一个线程,叫主线程。主线程又可以启动新的线程。上面的程序中,MainThread 就是主线程。在主线程下,利用threading.Thread(target, name)创建新的子线程。
如果不起名字,python默认子线程叫Thread-1,Thread-2….
在threading模块中,current_thread()函数,永远返回当前线程的实例。

Lock

多进程中,同一个变量,各有一份拷贝在每个进程中,互不影响,而多线程中,所有变量都由所有线程共享,这很容易导致,多个线程同时修改变量,将内容改乱。比如,

import time, threadingbalance = 0def change_blnc(n):    global balance    balance += n    balance -= n # 加减之后 balance应该为 0 def run_thread(n):    for i in range(10000000):        change_blnc(n)t1 = threading.Thread(target=run_thread, args=(7,), name='t1')t2 = threading.Thread(target=run_thread, args=(18,), name='t2')t1.start()t2.start()t1.join()t2.join()print(balance)1376

在两个线程t1,t2交替修改balance的时候,balance就不一定是0了。
在高级语言中,一条语句在CPU执行时是若干条语句。比如,balance += n
分为:
1.计算 balance + n 存入临时变量
2. 将临时变量的值赋给balance
也就是:

temp = balance + n
balance = temp

由于temp是局部变量,两个线程有自己的temp,当代码执行时:
t1: temp1 = balnace + 5 # temp1 = 0 + 5 = 5
t1: balance = temp1 # balance = 5
t1: temp1 = balance - 5 # temp1 = 5-5=0
t1: balance = temp1 # balance = 0

t2: temp2 = balance + 8 # temp2 = 8
t2: balance = temp2 # balance = 8
t2: temp2 = balance-8 # temp2 = 0
t2: balance = temp2 # balance = 0

如果t1与t2交替运行,操作系统以下面的顺序执行t1,t2:

balance = 0

t1: temp1 = balance + 5 # temp1 = 5

t2: temp2 = balance + 8 # temp2 = 8
t2: balance = temp2 # balance = 8

t1: balance = temp1 # balance = 5
t1: temp1 = balance - 5 # temp1 = 0
t1: balance = temp1 # balance = 0

t2: temp2 = balance -8 # temp2 = -8
t2: balance = temp2 # balance = -8

原因就是,修改balance需要多条语句执行,执行这些语句过程中,线程可能中断,从而导致多个线程把同一个对象的内容改乱。

所以,我们必须确保一个线程在修改数据时,别的线程不能访问这个数据。

这就是要在函数change_blnc()上加锁。当某个线程执行change_blnc()函数时,别的线程不能同时执行它,只能等待当前线程执行结束后,释放锁,才能执行它。同一时刻,只有一个线程持有该锁。

利用threading.Lock()实现线程锁的创建。

import threadingbalance = 0lock = threading.Lock()def run_thread(n):    for _ in range(10000000):        lock.acquire() # 加锁        try:            change_blnc(n)        finally:            lock.release() #解锁def change_blnc(n):    global balance    balance += n    balance -= n # 加减之后 balance应该为 0t1 = threading.Thread(target=run_thread, args=(7,), name='t1')   t2 = threading.Thread(target=run_thread, args=(18,), name='t2')   t1.start()t2.start()t1.join()t2.join()print(balance)0

当多个线程同时执行lock.acquire()时,只有一个线程能成功地获取锁,然后继续执行代码,其他线程就继续等待直到获得锁为止。
如果某一个线程使用完线程锁之后,没有释放,那么那些等待线程所得线程就会永远等待,成为死线程。所以要使用try…finally…的语句释放线程锁。

锁的好处就是确保了某段关键代码只能由一个线程从头到尾完整地执行,坏处当然也很多,首先是阻止了多线程并发执行,包含锁的某段代码实际上只能以单线程模式执行,效率就大大地下降了。其次,由于可以存在多个锁,不同的线程持有不同的锁,并试图获取对方持有的锁时,可能会造成死锁,导致多个线程全部挂起,既不能执行,也无法结束,只能靠操作系统强制终止。

多核CPU

在Python中,所有线程执行前都要获取全局解释锁(GIL),而GIL在每个CPU核心只有一个,所以多线程在Python中CPU利用率不高,不能利用多线程进行计算密集型的任务。反而,由于IO的时间远远大于CPU的时间,多线程往往能提高IO密集型的效率,虽然还是用了一个CPU核心。

鼎鼎大名的GIL锁,每执行100条字节码,解释器就自动释放GIL锁,让别的线程有机会执行。这个GIL全局锁实际上把所有线程的执行代码都给上了锁,所以,多线程在Python中只能交替执行,即使100个线程跑在100核CPU上,也只能用到1个核。

如果一定要通过多线程利用多核,那只能通过C扩展来实现,不过这样就失去了Python简单易用的特点。
不过,也不用过于担心,Python虽然不能利用多线程实现多核任务,但可以通过多进程实现多核任务。多个Python进程有各自独立的GIL锁,互不影响。

ThreadLocal

多线程情况下,每个线程都需要传入自己的数据。显然,传入的数据作为函数的局部变量比作为全局变量要好,因为局部变量不会受其他线程的影响。
以下情景中,参数作为局部变量传入多个函数:

def process_student(name):    std = Student(name)    # std是局部变量,但是每个函数都要用它,因此必须传进去:    do_task_1(std)    do_task_2(std)def do_task_1(std):    do_subtask_1(std)    do_subtask_2(std)def do_task_2(std):    do_subtask_2(std)    do_subtask_2(std)

每个函数一层一层调用都这么传参数那还得了?用全局变量?也不行,因为每个线程处理不同的Student对象,不能共享。

如果用一个全局dict存放所有的Student对象,然后以thread自身作为key获得线程对应的Student对象如何?

global_dict = {}def std_thread(name):    std = Student(name)    # 把std放到全局变量global_dict中:    global_dict[threading.current_thread()] = std    do_task_1()    do_task_2()def do_task_1():    # 不传入std,而是根据当前线程查找:    std = global_dict[threading.current_thread()]    ...def do_task_2():    # 任何函数都可以查找出当前线程的std变量:    std = global_dict[threading.current_thread()]    ...

这种方式理论上是可行的,它最大的优点是消除了std对象在每层函数中的传递问题,但是,每个函数获取std的代码有点丑。

有没有更简单的方式?

ThreadLocal应运而生,不用查找dict,ThreadLocal帮你自动做这件事:

import threading# 创建全局ThreadLocal对象:local_school = threading.local()def process_student():    # 获取当前线程关联的student:    std = local_school.student    print('Hello, {std} (in {name})'.format(std=std, name=threading.current_thread().name))def process_thread(name):    # 绑定ThreadLocal的student:    local_school.student = name    process_student()t1 = threading.Thread(target= process_thread, args=('Alice',), name='Thread-A')t2 = threading.Thread(target= process_thread, args=('Bob',), name='Thread-B')t2.start()t1.start()t1.join()t2.join()Hello, Bob (in Thread-B)Hello, Alice (in Thread-A)

全局变量local_school就是一个ThreadLocal对象,每个Thread对它都可以读写student属性,但互不影响。你可以把local_school看成全局变量,但每个属性如local_school.student都是线程的局部变量,可以任意读写而互不干扰,也不用管理锁的问题,ThreadLocal内部会处理。

可以理解为全局变量local_school是一个dict,不但可以用local_school.student,还可以绑定其他变量,如local_school.teacher等等。

ThreadLocal最常用的地方就是为每个线程绑定一个数据库连接,HTTP请求,用户身份信息等,这样一个线程的所有调用到的处理函数都可以非常方便地访问这些资源。

一个ThreadLocal变量虽然是全局变量,但每个线程都只能读写自己线程的独立副本,互不干扰。ThreadLocal解决了参数在一个线程中各个函数之间互相传递的问题。

0 0
原创粉丝点击