【Python】多线程 & 多进程(1)

由于GIL(全局解释器锁)的机制,Python同一时刻只有一个线程在跑。
因此 Python 的多线程实际仍然是串行执行,只对IO密集型程序有意义,对于CPU密集型程序,建议多进程

如果不确定多线程还是多进程,可以用 multiprocessing 的 dummy,他以多进程的API实现了多线程的机制

#多进程
from multiprocessing import Pool
#多线程
from multiprocessing.dummy import Pool
#看哪个快用哪个

多线程

Python提供两个模块实现多线程:thread 和 threading,后者是对前者的封装,不推荐用前者

基本用法

1)直接调用函数

import threading

def thread_func(num):
    print 'current thread: threading.currentThread().getName()'
    print '%d'%(num**2)

if __name__ == '__main__':
    thre = threading.Thread(target=thread_func, args=(2,))
    thre.start()
    thre.join()

2)封装成类
直接从 threading.Thread 继承

import threading

class myThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        # 其他需要用到的参数
        self.param1 = ...

    def run(self):
        thread_func(self.param1, ...)

def thread_func(param1,...):
   ...

# 创建新线程
thread = myThread(param1, ...)
# 开启线程
thread.start()

thread.join()

线程同步

1)互斥锁 Lock RLock

  • threading 提供了两种锁:LockRLock
  • 两种锁都实现了 acquire() 和 release() 方法
  • 如果一个锁的状态是 unlocked,调用 acquire() 会将其改变为 locked,调用 release() 会抛出异常
  • 如果一个锁的状态是 locked,调用 acquire() 会阻塞,知道其他线程调用 release() 释放锁
import threading

# 全局数据
count = 0
# 互斥锁
mutex = threading.Lock()

class MyThread(threading.Thread):
    def run(self):
        global count
        time.sleep(1)
        # 获取锁,修改资源
        if mutex.acquire():
            for i in range(100):
                count += 1
            print 'thread {} add 1, count is {}'.format(self.name, count)
            # 释放锁
            mutex.release()

        # 也可以用 with 自动实现 acquire 和 release
        with mutex:
            for i in range(100):
                count += 1
                print 'thread {} add 1, count is {}'.format(self.name, count)

RLock 的意义:

  • 考虑这样一种情况:一个函数内使用 Lock 保护了另一个子函数,但子函数内也用到这个 Lock来保护其他数据。这样就造成了死锁,因为子函数内的 Lock 需要等主函数的 Lock release 才能解除阻塞
  • 解决办法上就是,使用 RLock(递归锁)。它允许多次 acquire(release需要与之成对出现)
  • 因此保险起见,优先使用 RLock(mutex = threading.RLock())

2)条件变量 Condition

  • Condition 除了 acquire 和 release ,还提供了 wait 和 notify 方法对复杂线程同步问题做支持
  • 线程首先 acquire 一个条件变量,然后判断一些条件。如果条件不满足则 wait,并释放内部的锁;如果条件满足,进行一些处理改变条件后,通过 notify 通知其他线程,其他处于 wait 的线程接到通知后会重新判断条件
  • wait 要通过 notify 来解除阻塞,但 notify 并不会释放锁,还是需要显式 release 来释放
  • 与 Lock 和 RLock 一样,Condition 也支持上下文管理 with
  • 条件变量的一个典型应用是“生产消费者模型
# 摘自:http://www.cnblogs.com/holbrook/archive/2012/03/13/2394811.html

import threading
import time

class Producer(threading.Thread):
    def run(self):
        global count
        while True:
            if con.acquire():
                if count > 1000:
                    con.wait()
                else:
                    count = count+100
                    msg = self.name+' produce 100, count=' + str(count)
                    print msg
                    con.notify()
                con.release()
                time.sleep(1)

class Consumer(threading.Thread):
    def run(self):
        global count
        while True:
            if con.acquire():
                if count < 100:
                    con.wait()
                else:
                    count = count-3
                    msg = self.name+' consume 3, count='+str(count)
                    print msg
                    con.notify()
                con.release()
                time.sleep(1)

3)信号量 Semaphore

  • 互斥锁确保每次只有一个线程访问保护内容,信号量可以指定线程数目,每次允许该数目的线程同时访问
  • 每调用一次 acquire ,计数器减1;每调用一次 release,计数器加1;当计数器为0时,acquire被阻塞
import time
import threading
# 最多允许 3 个线程同时访问
semaphore = threading.Semaphore(3)

def func():
    if semaphore.acquire():
        for i in range(3):
            time.sleep(1)
            print (threading.currentThread().getName() + '获取锁')
        semaphore.release()
        print (threading.currentThread().getName() + ' 释放锁')

4)事件 Event

  • 一个线程通过 set 发送事件,另外的线程通过 wait 等待事件被触发
# 摘自:http://www.cnblogs.com/aguncn/p/6092611.html

event = threading.Event()
class Consumer(Thread):
    def __init__(self, items, event):
        Thread.__init__(self)
        self.items = items
        self.event = event

    def run(self):
        while True:
            time.sleep(2)
            #消费者等待事件被触发
            self.event.wait()
            item = self.items.pop()
            print("Consumer notify: %d poped from list by %s"
                  %(item, self.name))

class Producer(Thread):
    def __init__(self, items, event):
        Thread.__init__(self)
        self.items = items
        self.event = event

    def run(self):
        global item
        for i in range(10):
            time.sleep(2)
            item = random.randint(0, 256)
            self.items.append(item)
            print ("Producer nofity: item N %d appended to list by %s"
                   % (item, self.name))
            print ("Producer notify: event set by %s "
                   % self.name)
            # 生产者触发事件
            self.event.set()
            print("Produce notify: event clear by %s\n"
                  % self.name)
            self.event.clear()

5)队列 Queue

  • Queue并不是 threading 里的子模块,但其内部实现了锁的处理,自动实现线程同步
  • 提供了 3 种队列:
    Queue.Queue(maxsize) - 先进先出
    Queue.LifoQueue(maxsize) - 先进后出
    Queue.PriorityQueue(maxsize) - 优先级越低越先出来

如果 maxsize < 1 表示队列无限长
- 主要用到以下4个方法:

  • Queue.Queue.get([block [, timeout]]) - 删除并返回一个 item,block 默认为 True,表示当队列为空时阻塞线程,timeout 表示阻塞超时
  • Queue.Queue.put([block [, timeout]]) - 插入一个 item
  • Queue.Queue.task_done() - get 并处理完一个数据后调用 task_done 表示本任务完成
  • Queue.Queue.join() - 直到所有 item 都调用了 task_done 后主线程才继续执行
# 摘自: https://www.jianshu.com/p/0e4ff7c856d3

import Queue

queue = Queue.Queue(10)

class Producer(threading.Thread):

    def run(self):
        while True:
            elem = random.randrange(100)
            queue.put(elem)
            print "Producer a elem {}, Now size is {}".format(elem, queue.qsize())
            time.sleep(random.random())

class Consumer(threading.Thread):

    def run(self):
        while True:
            elem = queue.get()
            queue.task_done()
            print "Consumer a elem {}. Now size is {}".format(elem, queue.qsize())
            time.sleep(random.random())

后台线程

默认情况下,主线程退出后,子线程也会继续执行
如果希望子线程随主线程退出,使用 setDaemon(True)

t = MyThread()
        t.setDaemon(True)
        t.start()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值