Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Python(八)进程、线程、协程篇

$
0
0

本章内容:

线程(线程锁、threading.Event、queue 队列、 生产者消费者模型、自定义线程池 ) 进程(数据共享、进程池) 协程
Python(八)进程、线程、协程篇

线程

Threading用于提供线程相关的操作。线程是应用程序中工作的最小单元,它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。

threading 模块建立在 _thread 模块之上。thread 模块以低级、原始的方式来处理和控制线程,而 threading 模块通过对 thread 进行二次封装,提供了更方便的 api 来处理线程。

import threading
import time
def worker(num):
time.sleep(1)
print(num)
return
for i in range(10):
t = threading.Thread(target=worker, args=(i,), name="t.%d" % i)
t.start() # 继承式调用
import threading
import time
class MyThread(threading.Thread):
def __init__(self,num):
threading.Thread.__init__(self)
self.num = num
def run(self): #定义每个线程要运行的函数
print("running on number:%s" %self.num)
time.sleep(2)
if __name__ == '__main__':
t1 = MyThread(1)
t2 = MyThread(2)
t1.start()
t2.start()

thread方法:

t.start() : 激活线程 t.getName() : 获取线程的名称 t.setName() : 设置线程的名称 t.name: 获取或设置线程的名称 t.is_alive() : 判断线程是否为激活状态 t.isAlive() :判断线程是否为激活状态 t.setDaemon() 设置为后台线程或前台线程(默认:False);通过一个布尔值设置线程是否为守护线程,必须在执行start()方法之前才可以使用。如果是后台线程,主线程执行过程中,后台线程也在进行,主线程执行完毕后,后台线程不论成功与否,均停止;如果是前台线程,主线程执行过程中,前台线程也在进行,主线程执行完毕后,等待前台线程也执行完成后,程序停止 t.isDaemon() : 判断是否为守护线程 t.ident :获取线程的标识符。线程标识符是一个非零整数,只有在调用了start()方法之后该属性才有效,否则它只返回None t.join() :逐个执行每个线程,执行完毕后继续往下执行,该方法使得多线程变得无意义 t.run() :线程被cpu调度后自动执行线程对象的run方法

线程锁

threading.RLock & threading.Lock

我们使用线程对数据进行操作的时候,如果多个线程同时修改某个数据,可能会出现不可预料的结果,为了保证数据的准确性,引入了锁的概念。

import threading
import time
num = 0
lock = threading.RLock() # 实例化锁类
def work():
lock.acquire() # 加锁
global num
num += 1
time.sleep(1)
print(num)
lock.release() # 解锁
for i in range(10):
t = threading.Thread(target=work)
t.start()

threading.RLock和threading.Lock 的区别

RLock允许在同一线程中被多次acquire。而Lock却不允许这种情况。 如果使用RLock,那么acquire和release必须成对出现,即调用了n次acquire,必须调用n次的release才能真正释放所占用的锁。

import threading
lock = threading.Lock()
lock.acquire()
lock.acquire() # 产生死锁
lock.release()
lock.release() import threading
rlock = threading.RLock()
rlock.acquire()
rlock.acquire() # 在同一线程内,程序不会堵塞。
rlock.release()
rlock.release()
print("end.")

threading.Event

Event是线程间通信最间的机制之一:一个线程发送一个event信号,其他的线程则等待这个信号。用于主线程控制其他线程的执行。 Events 管理一个flag,这个flag可以使用set()设置成True或者使用clear()重置为False,wait()则用于阻塞,在flag为True之前。flag默认为False。

Event.wait([timeout]) : 堵塞线程,直到Event对象内部标识位被设为True或超时(如果提供了参数timeout) Event.set() :将标识位设为Ture Event.clear() : 将标识伴设为False Event.isSet() :判断标识位是否为Ture import threading
def do(event):
print('start')
event.wait()
print('execute')
event_obj = threading.Event()
for i in range(10):
t = threading.Thread(target=do, args=(event_obj,))
t.start()
event_obj.clear()
inp = input('input:')
if inp == 'true':
event_obj.set()

当线程执行的时候,如果flag为False,则线程会阻塞,当flag为True的时候,线程不会阻塞。它提供了本地和远程的并发性。

threading.Condition

python提供的Condition对象提供了对复杂线程同步问题的支持。Condition被称为条件变量,除了提供与Lock类似的acquire和release方法外,还提供了wait和notify方法。线程首先acquire一个条件变量,然后判断一些条件。如果条件不满足则wait;如果条件满足,进行一些处理改变条件后,通过notify方法通知其他线程,其他处于wait状态的线程接到通知后会重新判断条件。不断的重复这一过程,从而解决复杂的同步问题。

在典型的设计风格里,利用condition变量用锁去通许访问一些共享状态,线程在获取到它想得到的状态前,会反复调用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: 任务函数

Viewing all articles
Browse latest Browse all 9596

Trending Articles