python----线程进程协程
python线程:
import threading import time def show(arg): time.sleep(1) print('thread' + str(arg)) for i in range(10): t = threading.Thread(target=show, args=(i,)) t.start() print('main thread stop')
import threading class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): print("线程开始运行") t1 = MyThread() t1.start()
更多方法:
- start 线程准备就绪,等待CPU调度
- setName 为线程设置名称
- getName 获取线程名称
- setDaemon 设置为后台线程或前台线程(默认) t.setDaemon(True) 必须在 t.start() 之前调用
如果是后台线程,主线程执行过程中,后台线程也在进行,主线程执行完毕后,后台线程不论成功与否,均停止
如果是前台线程,主线程执行过程中,前台线程也在进行,主线程执行完毕后,等待前台线程也执行完成后,程序停止 - join 逐个执行每个线程,执行完毕后继续往下执行,该方法使得多线程变得无意义
- run 线程被cpu调度后自动执行线程对象的run方法
线程池
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ProcessPoolExecutor import time def foo(i): time.sleep(1) print(i) pool = ThreadPoolExecutor(2) #线程池 pool2 = ProcessPoolExecutor(2) #进程池 if __name__ == '__main__': for i in range(10): pool.submit(foo, i)
#pool.submit(get_page,detail_url).add_done_callback(call_back_function) #设置回调函数
线程锁
import threading import time gl_num = 0 lock = threading.RLock() def Func(): lock.acquire() global gl_num try: gl_num += 1 print(gl_num) finally: #防止死锁 lock.release() for i in range(10): t = threading.Thread(target=Func) t.start()
信号量(Semaphore)
互斥锁 同时只允许一个线程更改数据,而Semaphore是同时允许一定数量的线程更改数据 ,比如厕所有3个坑,那最多只允许3个人上厕所,后面的人只能等里面有人出来了才能再进去。
import threading, time semaphore = threading.BoundedSemaphore(2) # 最多允许2个线程同时运行 def run(n): semaphore.acquire() time.sleep(1) print("run the thread: %s" % n) semaphore.release() if __name__ == '__main__': num = 0 for i in range(20): t = threading.Thread(target=run, args=(i,)) t.start()
事件(event)
python线程的事件用于主线程控制其他线程的执行,事件主要提供了三个方法 set、wait、clear。
事件处理的机制:全局定义了一个“Flag”,如果“Flag”值为 False,那么当程序执行 event.wait 方法时就会阻塞,如果“Flag”值为True,那么event.wait 方法时便不再阻塞。
- clear:将“Flag”设置为False
- set:将“Flag”设置为True
import threading def do(event_obj): print( 'start') event_obj.wait() print('execute')
event_obj = threading.Event() #创建event对象 for i in range(10): t = threading.Thread(target=do, args=(event_obj,)) t.start() event_obj.clear() #默认Flag为False inp = input('input:') if inp == 'true': event_obj.set()
条件(Condition)
使得线程等待,只有满足某条件时,才释放n个线程
acquire([timeout])/release(): 调用关联的锁的相应方法。
wait([timeout]): 调用这个方法将使线程进入Condition的等待池等待通知,并释放锁。使用前线程必须已获得锁定,否则将抛出异常。
notify(): 调用这个方法将从等待池挑选一个线程并通知,收到通知的线程将自动调用acquire()尝试获得锁定(进入锁定池);其他线程仍然在等待池中。调用这个方法不会释放锁定。使用前线程必须已获得锁定,否则将抛出异常。
notifyAll(): 调用这个方法将通知等待池中所有的线程,这些线程都将进入锁定池尝试获得锁定。调用这个方法不会释放锁定。使用前线程必须已获得锁定,否则将抛出异常。
import threading
def run(n):
con.acquire() #用来加锁
con.wait() #用来接收通知
print("run the thread: %s" % n)
con.release()
if __name__ == '__main__':
con = threading.Condition()
for i in range(10):
t = threading.Thread(target=run, args=(i,))
t.setDaemon(True)
t.start()
while True:
inp = input('>>>') #输入数字
if inp == 'q':
break
con.acquire()
con.notify(int(inp)) #执行inp个线程(此时有10个线程开启了,notify会挑选inp个线程进行通知)
# con.notify() #默认通知一个
con.release()
#优点类似yield import threading import time import datetime num = 0 con = threading.Condition() class Gov(threading.Thread): def __init__(self): super(Gov, self).__init__() def run(self): global num con.acquire() while True: print("开始拉升股市") num += 1 print("拉升了" + str(num) + "个点") time.sleep(2) if num == 5: print("暂时安全!") con.notify() con.wait() con.release() class Consumers(threading.Thread): def __init__(self): super(Consumers, self).__init__() def run(self): global num con.acquire() while True: if num > 0: print("开始打压股市") num -= 1 print("打压了" + str(num) + "个点") time.sleep(2) if num == 0: print("你妹的!天台在哪里!") con.notify() con.wait() con.release() if __name__ == '__main__': p = Gov() c = Consumers() p.start() c.start()