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')
importthreadingclassMyThread(threading.Thread):def __init__(self):
threading.Thread.__init__(self)defrun(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) #设置回调函数
线程锁
importthreadingimporttime
gl_num=0
lock=threading.RLock()defFunc():
lock.acquire()globalgl_numtry:
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个人上厕所,后面的人只能等里面有人出来了才能再进去。
importthreading, time
semaphore= threading.BoundedSemaphore(2) #最多允许2个线程同时运行
defrun(n):
semaphore.acquire()
time.sleep(1)print("run the thread: %s" %n)
semaphore.release()if __name__ == '__main__':
num=0for 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
importthreadingdefdo(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
importthreadingimporttimeimportdatetime
num=0
con=threading.Condition()classGov(threading.Thread):def __init__(self):
super(Gov, self).__init__()defrun(self):globalnum
con.acquire()whileTrue:print("开始拉升股市")
num+= 1
print("拉升了" + str(num) + "个点")
time.sleep(2)if num == 5:print("暂时安全!")
con.notify()
con.wait()
con.release()classConsumers(threading.Thread):def __init__(self):
super(Consumers, self).__init__()defrun(self):globalnum
con.acquire()whileTrue: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()
额外例子
importthreadingdefcondition_func():
ret=False
inp= input('>>>')if inp == '1':
ret=Truereturnretdefrun(n):
con.acquire()
con.wait_for(condition_func)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.start()
额外例子
Timer
定时器,指定n秒后执行某操作
from threading importTimerdefhello():print("hello, world")
t= Timer(1, hello)
t.start()
python进程:
from multiprocessing importProcessdeffoo(i):print('say hi', i)if __name__ == '__main__':for i in range(10):
p= Process(target=foo, args=(i,))
p.start()
进程数据共享
进程各自持有一份数据,默认无法共享数据
from multiprocessing importProcess
li=[]deffoo(i):
li.append(i)#每个进程都有一份li,并将自己的[i]append进去
print('say hi', li,i)if __name__ == '__main__':for i in range(10):
p= Process(target=foo, args=(i,))
p.start()importtime
time.sleep(2)print('ending', li) #主进程的li为空
实现数据共享
方法一:利用Array
from multiprocessing importProcess, Array
temp= Array('i', [11, 22, 33, 44])defFoo(temp,i):
temp[i]= 100 + i #需要将temp传递给每一个进程实现数据共享(利用Array)
print(temp[:])if __name__ == '__main__':for i in range(2):
p= Process(target=Foo, args=(temp,i,))
p.start()
p.join()print(temp[:])
方法二,利用Managefrom multiprocessing importProcess, Managerimportmultiprocessing
lock=multiprocessing.Lock()defFoo(dic,i):
dic[i]= "b"
if __name__ == '__main__':
manage=Manager()
dic=manage.dict()for i in range(2):
p= Process(target=Foo, args=(dic,i,))
p.start()
p.join()#猜测目的是让主进程不能断,可能会对dic造成影响。
print(dic)
from multiprocessing importProcess, Queuedeff(i,q):
q.put(i)if __name__ == '__main__':
q=Queue()for i in range(10):
p= Process(target=f, args=(i,q,))
p.start()whileTrue:print(q.get())
使用Queue
进程锁
from multiprocessing importProcess, Array, RLockdefFoo(lock,temp,i):
lock.acquire()
temp[i]= 100+iprint(temp[:],i)
lock.release()
lock=RLock()
temp= Array('i', [11, 22, 33, 44])if __name__ == '__main__':for i in range(4):
p= Process(target=Foo, args=(lock, temp, i,))
p.start()
进程池
from multiprocessing importProcess, PoolimporttimedefFoo(i):
time.sleep(1)return i + 100
defBar(arg):print(arg)if __name__ == '__main__':
pool= Pool(5)#print(pool.apply(Foo, (1,))) #apply是阻塞的,所以进入子进程执行后,等待当前子进程执行完毕,在继续执行下一个进程
#print(pool.apply_async(func=Foo, args=(1,)).get()) #apply_async 是异步非阻塞的。有系统调用进程切换
for i in range(10):
pool.apply_async(func=Foo, args=(i,), callback=Bar)
pool.close()
pool.join()#进程池中进程执行完毕后再关闭,如果注释,那么程序直接关闭。
print('end')
python协程:
线程和进程的操作是由程序触发系统接口,最后的执行者是系统;协程的操作则是程序员
协程的适用场景:当程序中存在大量不需要CPU的操作时(IO),适用于协程;
利用greenlet:
from greenlet importgreenletdeftest1():print(1)
gr2.switch()print(2)
gr2.switch()deftest2():print(3)
gr1.switch()print(4)
gr1=greenlet(test1)
gr2=greenlet(test2)
gr1.switch()
利用gevent:
importgeventdeffoo():print('start foo')
gevent.sleep(0)#目的造成io堵塞,让线程切换到bar函数上
print('end foo')defbar():print('start bar')
gevent.sleep(0)print('end bar')
gevent.joinall([
gevent.spawn(foo),
gevent.spawn(bar),
])
from gevent importmonkey
monkey.patch_all()#必须加
importgeventimportrequestsdeff(url):print('GET: %s' %url)
response= requests.request(url=url,method="GET")
data=response.textprint('%d bytes received from %s.' %(len(data), url))
gevent.joinall([
gevent.spawn(f,'https://www.python.org/'),
gevent.spawn(f,'https://www.yahoo.com/'),
gevent.spawn(f,'https://github.com/'),
])
gevent实用场景
补充猴子补丁:
使用猴子补丁的方式,gevent能够修改标准库里面大部分的阻塞式系统调用,包括socket、ssl、threading和 select等模块,而变为协作式运行。也就是通过猴子补丁的monkey.patch_xxx()来将python标准库中模块或函数改成gevent中的响应的具有协程的协作式对象。这样在不改变原有代码的情况下,将应用的阻塞式方法,变成协程式的。
猴子补丁的功能很强大,但是也带来了很多的风险,尤其是像gevent这种直接进行API替换的补丁,整个Python进程所使用的模块都会被替换,可能自己的代码能hold住
importsocketimportselectfrom gevent importmonkeyprint(socket.socket)
monkey.patch_socket()print(socket.socket,'after socket')print(select.select,)
monkey.patch_select()print(select.select,"after select")