设为首页 加入收藏

TOP

Python(八)进程、线程、协程篇(二)
2017-09-30 16:10:46 】 浏览:421
Tags:Python 进程 线程 程篇
量用锁去通许访问一些共享状态,线程在获取到它想得到的状态前,会反复调用wait()。修改状态的线程在他们状态改变时调用 notify() or notify_all(),用这种方式,线程会尽可能的获取到想要的一个等待者状态。

import threading
import time
def consumer(cond): with cond: print("consumer before wait") cond.wait() print("consumer after wait") def producer(cond): with cond: print("producer before notifyAll") cond.notifyAll() print("producer after notifyAll") condition = threading.Condition() c1 = threading.Thread(name="c1", target=consumer, args=(condition,)) c2 = threading.Thread(name="c2", target=consumer, args=(condition,)) p = threading.Thread(name="p", target=producer, args=(condition,)) c1.start() time.sleep(2) c2.start() time.sleep(2) p.start() # consumer()线程要等待producer()设置了Condition之后才能继续。

  

queue 队列

适用于多线程编程的先进先出数据结构,可以用来安全的传递多线程信息。

queue 方法:

  • q = queue.Queue(maxsize=0) # 构造一个先进显出队列,maxsize指定队列长度,为0 时,表示队列长度无限制。
  • q.join()   # 等到队列为kong的时候,在执行别的操作
  • q.qsize()   # 返回队列的大小 (不可靠)
  • q.empty()    # 当队列为空的时候,返回True 否则返回False (不可靠)
  • q.full()     # 当队列满的时候,返回True,否则返回False (不可靠)
  • q.put(item, block=True, timeout=None) # 将item放入Queue尾部,item必须存在,可以参数block默认为True,表示当队列满时,会等待队列给出可用位置,为False时为非阻塞,此时如果队列已满,会引发queue.Full 异常。 可选参数timeout,表示 会阻塞设置的时间,过后,如果队列无法给出放入item的位置,则引发 queue.Full 异常
  • q.get(block=True, timeout=None) # 移除并返回队列头部的一个值,可选参数block默认为True,表示获取值的时候,如果队列为空,则阻塞,为False时,不阻塞,若此时队列为空,则引发 queue.Empty异常。 可选参数timeout,表示会阻塞设置的时候,过后,如果队列为空,则引发Empty异常。
  • q.put_nowait(item) # 等效于 put(item,block=False)
  • q.get_nowait()     # 等效于 get(item,block=False)

生产者消费者模型

import queue
import threading

que = queue.Queue(10)

def s(i):
    que.put(i)
    # print("size:", que.qsize())

def x(i):
    g = que.get(i)
    print("get:", g)

for i in range(1, 13):
    t = threading.Thread(target=s, args=(i,))
    t.start()

for i in range(1, 11):
    t = threading.Thread(target=x, args=(i,))
    t.start()
    
print("size:", que.qsize())

# 输出结果:
get: 1
get: 2
get: 3
get: 4
get: 5
get: 6
get: 7
get: 8
get: 9
get: 10
size: 2

 

自定义线程池:

# 自定义线程池(一)
import queue
import threading
import time

class TreadPool:

    def __init__(self, max_num=20):
        self.queue = queue.Queue(max_num)
        for i in range(max_num):
            self.queue.put(threading.Thread)

    def get_thread(self):
        return self.queue.get()

    def add_thread(self):
        self.queue.put(threading.Thread)

def func(pool, n):
    time.sleep(1)
    print(n)
    pool.add_thread()

p = TreadPool(10)
for i in range(1, 100):
    thread = p.get_thread()
    t = thread(target=func, args=(p, i,))
    t.start()
自定义线程池(一)
# 线程池(二)
import queue
import threading
import contextlib
import time

StopEvent = object()

class Threadpool:

    def __init__(self, max_num=10):
        self.q = queue.Queue()
        self.max_num = max_num

        self.terminal = False
        self.generate_list = []     # 以创建线程列表
        self.free_list = []         # 以创建的线程空闲列表

    def run(self, func, args, callback=None):
        """
        线程池执行一个任务
        :param func: 任务函数
        :param args: 任务函数所需参数
        :param callback: 任务执行失败或成功后执行的回调函数,回调函数有两个参数1、任务函数执行状态;2、任务函数返回值(默认为None,即:不执行回调函数)
        :return: 如果线程池已经终止,则返回True否则None
        """
        if len(se
首页 上一页 1 2 3 4 5 下一页 尾页 2/5/5
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇python 之 赋值和拷贝(你真的了.. 下一篇[Django]用户权限学习系列之设计..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目