首页 > 编程语言 > 详细

线程模块

时间:2019-05-21 18:16:31      阅读:113      评论:0      收藏:0      [点我收藏+]

信号量

技术分享图片
from threading import Semaphore,Thread
import time

def func(a,b):
    time.sleep(1)
    sem.acquire()
    print(a+b)
    sem.release()

sem = Semaphore(4)
for i in range(10):
    t = Thread(target=func,args=(i,i+5))
    t.start()
信号量

事件

技术分享图片
# 事件被创建的时候,默认为False状态
# Flase状态   wait()阻塞
# True 状态   wait()非阻塞
# clear 设置状态为False
# set   设置状态位True

# 连接数据库
# 检测数据库的可连接情况

import time
import random
from threading import Thread,Event

def connect_db(e):
    count = 0
    while count<3:
        e.wait(0.5)       # 状态为False的时候,只等待1秒就结束
        if e.is_set():
            print(连接数据库)
            break
        else:

            print(第%s次连接失败%(count+1))
            count += 1
    else:
        raise TimeoutError(数据库连接超时)

def check_web(e):
    time.sleep(random.randint(0,3))
    e.set()

e = Event()
t1 = Thread(target=connect_db,args=(e,))
t2 = Thread(target=check_web,args=(e,))
t1.start()
t2.start()
事件

条件:

条件——锁
一个条件被创建之初,默认有一个False状态
False状态,会影响wait一直处于等待状态
notify(int数据类型) 制作一串钥匙
技术分享图片
from threading import Condition,Thread


def func(con,i):
    con.acquire()
    con.wait()
    print(在第%s个循环% i)
    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()
条件

定时器

技术分享图片
from threading import Timer
import time
def func():
    print(时间同步)

while True:
    Timer(2,func).start()
    time.sleep(2)
定时器

队列

技术分享图片
# queue
# 队列的特点:先进先出
# import queue
# q = queue.Queue()
# q.put()
# q.get()
# q.put_nowait()
# q.get_nowait()

# 栈     先进后出
# import queue
# q = queue.LifoQueue()
# q.put(1)
#
# q.put(2)
# q.put(3)
# print(q.get())

# 优先级队列     数值越低优先级越高,优先级一样按照ASCII码排
# import queue
# q = queue.PriorityQueue()
# q.put((20,‘a‘))
# q.put((10,‘b‘))
# q.put((40,‘c‘))
# q.put((2,‘e‘))
# q.put((2,‘d‘))
# print(q.get())
三种队列

线程池

技术分享图片
from concurrent.futures import ThreadPoolExecutor
import time
def func(n):
    time.sleep(2)
    print(n)
    return n*n
def call_back(m):
    print(结果是:,m.result())

tpool = ThreadPoolExecutor(max_workers=5)   # 默认 不要超过cpu个数*5
for i in range(20):
    t = tpool.submit(func,i).add_done_callback(call_back)

# tpool.map(func,range(20))
# t_lst = []
# for i in range(20):
#     t = tpool.submit(func,i)
#     t_lst.append(t)
# # tpool.shutdown()    #close+join
# print(‘主线程‘)
# for t in t_lst:print(‘****‘,t.result())

# 起进程池的话和线程池一模一样,改个名字就可以了
线程池

 

线程模块

原文:https://www.cnblogs.com/Mr-Feng/p/10901378.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!