7.22 python线程(3)

2018-7-22 10:28:29 回来啦!

6.条件

# !/usr/bin/env python
# !--*--coding:utf-8 --*--
# !@Time    :2018/7/20 18:01
# !@Author   TrueNewBee
# 条件
# 2018-7-20 18:47:17 去俺弟弟家玩去,后天归来
# 2018-7-22 10:18:03 回来了
# 条件
#
# acquire release
# 一个条件被创建之初 默认有一个False状态
# False状态 会影响wait()一直处于等待状态
# notify(int数据类型) 制造一串钥匙
# 不大重要,只能停留在面试中
from threading import Condition, Thread


def func(con1, i1):
    con1.acquire()
    con1.wait()     # 等钥匙
    print('在第%s个循环里' % i1)
    con.release()


con = Condition()
for i in range(10):
    Thread(target=func, args=(con, i)).start()
while True:
    num = int(input('>>>'))
    con.acquire()
    con.notify(num)     # 造钥匙
    con.release()

7.定时器

# !/usr/bin/env python
# !--*--coding:utf-8 --*--
# !@Time    :2018/7/22 10:30
# !@Author   TrueNewBee
# 用的不多,知道这个组件就好了
import time
from threading import Timer


def func():
    print('时间同步')


if __name__ == '__main__':
    while True:
        Timer(5, func).start()  # 非阻塞的
        time.sleep(5)

8.队列

# !/usr/bin/env python
# !--*--coding:utf-8 --*--
# !@Time    :2018/7/22 10:49
# !@Author   TrueNewBee
# queue
import queue


q = queue.Queue()   # 队列先进先出
# q.put()
# q.get()
# q.put_nowait()
# q.get_nowait()


queue.LifoQueue()   # 栈 先进后出
q.put((50, 'a'))
q.put((30, 'r'))
q.put((1, 'z'))
q.put((1, 'd'))

print(q.get())

9.池

# !/usr/bin/env python
# !--*--coding:utf-8 --*--
# !@Time    :2018/7/22 11:19
# !@Author   TrueNewBee
import time
from concurrent.futures import ThreadPoolExecutor


def func(n):
    time.sleep(2)
    print(n)
    return n*n


tpool= ThreadPoolExecutor(max_workers=5)   # 默认 不要超过cpu个数*5
t_list = []
for i in range(20):
    t = tpool.submit(func, i)   # 异步提交任务
    t_list.append(t)
tpool.shutdown()  # close+join
print('主线程')
for t in t_list:
    print('****', t.result())
原文地址:https://www.cnblogs.com/zhen1996/p/9349617.html