
本文共 25953 字,大约阅读时间需要 86 分钟。
���������
- ������������������
- ���������������������������
- ������������������������
- Thread������������������������������
- ������������
- ������������������������
- ������������Event���������
- ������Queue
- ���������������������
������������������
���������������������������������������������������������������������������������������������������
���������������������������������������������������������������������������������������������������������������CPU������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
���������������������������������������������������������������������CPU���������������������
������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
so������������������������������������������������������������������
���������������������������
# ���������from threading import Threadimport timedef task(name): print('%s is running.'%name) time.sleep(2) print('%s is done.'%name)if __name__ == '__main__': t = Thread(target=task,args=('���������',)) t.start() print('���������')# ��������������������� is running.������������������ is done.---------------------------------------------------# ���������from threading import Threadimport timeclass MyThread(Thread): def __init__(self,name): super(MyThread, self).__init__() self.name = name def run(self): print('%s is running.'%self.name) time.sleep(2) print('%s is done.'%self.name)if __name__ == '__main__': t = MyThread('���������') t.start() print('���������')# ��������������������� is running.������������������ is done.
������������������������
- ������������������������������������
- ������������������������������������������������������������
- PID
������������������������������������������
# ���������������from multiprocessing import Processimport timeclass MyProcess(Process): def __init__(self,name): super(MyProcess, self).__init__() self.name = name def run(self): print('%s is running.'%self.name) time.sleep(2) print('%s is done.'%self.name)if __name__ == '__main__': p = MyProcess('���������') p.start() print('���������')
# ���������������from threading import Threadimport timeclass MyThread(Thread): def __init__(self,name): super(MyThread, self).__init__() self.name = name def run(self): print('%s is running.'%self.name) time.sleep(2) print('%s is done.'%self.name)if __name__ == '__main__': p = MyThread('���������') p.start() print('���������')
������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
���������������������������������������������������������������������������������
���������������������������������������������������������������
������������������������������������������������������������������������������������������������������������������������������������������������������������
from threading import Threadfrom multiprocessing import Processimport timen = 100def task(name): global n n = 99 print('[%s]���n���������<%s>'%(name,n))if __name__ == '__main__': t = Thread(target=task,args=('���������',)) t.start() print('���������n���������%s'%n)# ���������������[���������]���n���������<99>���������n���������99
���������������������������������������������
���������pid
# ������������������������������pidfrom multiprocessing import Process,current_processimport timedef task(): print('���������:',current_process().pid) time.sleep(2)if __name__ == '__main__': p = Process(target=task,name='���������') p.start() print('���������:',current_process().pid) # ���������������:���������: 7912���������: 12092
# ������������������������������pidfrom threading import Thread,current_threadimport time,osdef task(): print('���������:',os.getpid()) time.sleep(2)if __name__ == '__main__': t = Thread(target=task,name='Thread���������') t.start() print('���������:',os.getpid()) # ���������������������������: 9060���������: 9060 ������������������������������������������������������������������������������������������������������������������'���������'
Thread������������������������
name���getName()���������������name������������������������getName���������������������
from threading import Thread,current_threadimport time,osdef task(): print('���������������:',current_thread().getName()) # ��������������������������� time.sleep(2)if __name__ == '__main__': t = Thread(target=task,name='Thread���������') # ������������������������ t.start() print('���������') # ������������������������������������: Thread���������
join()���������is_alive()������
join()���������������������������������������������������������is_alive()������������������������������������
from threading import Thread,current_threadimport time,osdef task(name): print('%s is running'%name) time.sleep(2) print('%s is done'%name)if __name__ == '__main__': t = Thread(target=task,args=('���������1',)) t.start() print(t.is_alive()) # ������������������ t.join() #������������������ print('���������') print(t.is_alive()) # ������������������ # ������������������������1 is runningTrue���������1 is done���������False
active_count()���������������������������
from threading import Thread,current_thread,active_count # ������������������import time,osdef task(name): print('%s is running'%name) time.sleep(2) print('%s is done'%name)if __name__ == '__main__': t1 = Thread(target=task,args=('���������1',)) t2 = Thread(target=task,args=('���������2',)) t1.start() t2.start() print(active_count()) # ��������������������� t1.join() t2.join() print('���������') # ���������������������1 is running���������2 is running3���������2 is done���������1 is done���������
eumecate()������������������������������������
from threading import Thread,current_thread,active_count,enumerateimport time,osdef task(name): print('%s is running'%name) time.sleep(2) print('%s is done'%name)if __name__ == '__main__': t1 = Thread(target=task,args=('���������1',)) t2 = Thread(target=task,args=('���������2',)) t1.start() t2.start() print('���������������������������',active_count()) print('���������������������������',enumerate()) print('���������') # ������������������������1 is running���������2 is running��������������������������� 3��������������������������� [<_MainThread(MainThread, started 14472)>,, ]������������������1 is done���������2 is done
������������
������������������������������������������������xx������������xx������������������������
������������������������������������������������������
1.���������������������������������������������������������������������2.������������������������������������������������������������������������������������������������������������������������������������������������
���������������
1.������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������2.���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
������������
# ������������������from threading import Threadimport timedef sayhi(name): time.sleep(2) print('%s is say hello'%name)if __name__ == '__main__': t = Thread(target=sayhi,args=('���������')) # t.setDaemon(True) # ������������������������ t.daemon = True t.start() print('���������') # ������������������������������ print(t.is_alive()) # ������������������������ # ���������������������������True
# ���������������from threading import Threadimport timedef foo(): print(123) time.sleep(2) print('end123')def bar(): print(456) time.sleep(2) print('end456')if __name__ == '__main__': t1 = Thread(target=foo,) t2 = Thread(target=bar,) t1.daemon = True # ���t1������������������������ t1.start() t2.start() print('���������') # ��������������� # ������������������123456���������end123end456
������������������������
������������
���������������������������������������������/������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
# ������from threading import Thread,Lockimport time# ������A������B���mutexA = Lock() # ���������������acquire������mutexB = Lock()class MyThread(Thread): def run(self): self.f1() self.f2() def f1(self): mutexA.acquire() print('%s ���������A���'%self.name) mutexB.acquire() print('%s ���������B���'%self.name) mutexB.release() mutexA.release() def f2(self): mutexB.acquire() print('%s ���������B���'%self.name) time.sleep(0.05) mutexA.acquire() print('%s ���������A���'%self.name) mutexA.release() mutexB.release()if __name__ == '__main__': for i in range(10): t = MyThread() t.start() # ������run������ # ������������������Thread-1 ���������A���Thread-1 ���������B���Thread-1 ���������B���Thread-2 ���������A���������������������������������f2 ���������������������mutexB������������������������������������0.05s������������������������������������IO������������������COU���������Thread-2���������������Thread-2���������mutexA���������������������������������
���������������������������������������������
���������
������������������������������������acquire���������������������������������acquire������������������������acquire������������������������������������1������release������������������1���������������0������������������������������������acquire���
# ���������������������������������from threading import Thread,RLockimport time# ���������mutexA = RLock()mutexB = mutexA # ������������������class MyThread(Thread): def run(self): self.f1() self.f2() def f1(self): mutexA.acquire() print('%s ���������A���'%self.name) mutexB.acquire() print('%s ���������B���'%self.name) mutexB.release() mutexA.release() def f2(self): mutexB.acquire() print('%s ���������B���'%self.name) time.sleep(1) mutexA.acquire() print('%s ���������A���'%self.name) mutexA.release() mutexB.release()if __name__ == '__main__': for i in range(10): t = MyThread() t.start()
���������
������������������������������������������������������������������������������������������������������������������������������5���������������������������������5���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
# ���������from threading import Thread,Semaphore,current_threadimport time,randomsm = Semaphore(3) # ������������������������3def task(): sm.acquire() print('%s in'%current_thread().getName()) time.sleep(random.randint(1,3)) sm.release()if __name__ == '__main__': for i in range(10): t = Thread(target=task,) t.start() # ���������������Thread-1 inThread-2 inThread-3 inThread-4 inThread-5 inThread-6 inThread-7 inThread-8 inThread-9 inThread-10 in# ��������������������������������������������������������� with sm: print('%s in '%current_thread().getName()) time.sleep(random.randint(1,3))
������
Semaphore������������������������������������������acquire()���������������������-1������release()������������������+1���������������������0������������������0������acquire()���������������������������������������release()
Event���������
���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������threading���������Event���������������������������������������������������������������������������������������������������������������������������������Event���������������������������������������False������������������������Event������������������Event������������������������������������������������������������������������������������������������������������������Event������������������������������������������������������������������Event���������������������������������������������������������������������������Event���������������������������������������������������������
from Threading import Eventevent = Event()event.isSet() # ������event������������event.wait() # ������event.isSet == False������������������event.set() # ������event���������������True������������������������������������������������������������������������event.clear() # ������event���������������True
������������������������������������������������������������������������������������������������������
from threading import Thread,Eventimport timeevent = Event()def student(name): print('%s ������������'%name) event.wait() print('%s ������������'%name)def teacher(name): print('������ %s ������������ '%name) time.sleep(7) event.set()if __name__ == '__main__': stu1 = Thread(target=student,args=('������',)) stu2 = Thread(target=student,args=('������',)) stu3 = Thread(target=student,args=('���������',)) t1 = Thread(target=teacher,args=('���������',)) stu1.start() stu2.start() stu3.start() t1.start()# ������������������ ������������������ ��������������������� ������������������ ��������� ������������ ������ ��������������������� ������������������ ������������
���������������������������������������������������������������
from threading import Thread,Eventimport timeevent = Event()def student(name): print('������ <%s> ������������'%name) event.wait(3) # ���������������������������2��������� print('������ <%s> ������������'%name)def teacher(name): print('%s ������������'%name) time.sleep(7) event.set()if __name__ == '__main__': stu1 = Thread(target=student,args=('������',)) stu2 = Thread(target=student,args=('������',)) stu3 = Thread(target=student,args=('������',)) t1 = Thread(target=teacher,args=('���������',)) stu1.start() stu2.start() stu3.start() t1.start() # ������������������ <������> ������������������ <������> ������������������ <������> ��������������������� ������������������ <������> ������������ # 3s��������������������������� <������> ������������������ <������> ������������
������������������������������������������MySQL���������������������������������MySQL������������������������������������������������MySQL������������������������������������������������������������������������������������Event������������������������������������������������
# ������mysql������from threading import Thread,Event,current_threadimport time,random# ������������������������event = Event()def conn_mysql(): count = 1 while not event.is_set(): # ���������False if count > 3: raise TimeoutError('������������') print('<%s> ���%s���������������'%(current_thread().getName(),count)) event.wait(0.5) count += 1 print('<%s> ������������'%current_thread().getName())def check_mysql(): print('%s is checking'%current_thread().getName()) time.sleep(5) event.set()if __name__ == '__main__': for i in range(3): t = Thread(target=conn_mysql,) t.start() t = Thread(target=check_mysql) t.start()# ������������������1��������������� ���1��������������� ���1���������������Thread-4 is checking ������������ ������������ ������������ ���2��������������� ���2��������������� ���2��������������� ������������ ������������ ���3��������������� ������������ ���3��������������� ���3��������������� ������������ ������������ ������������
���������
������������������n���������������������
# ���������from threading import Timerdef hello(): print('hello world')t = Timer(2,hello)t.start()
������������������������������������
# ������������������������������������from threading import Thread,Timerimport randomclass Code(): def __init__(self): self.make_cache() # ��������������������������������������������� def make_cache(self,interval=5): self.cache = self.make_code() print(self.cache) self.t = Timer(interval,self.make_cache) self.t.start() # ��������������� def make_code(self,n=4): # ������������������ res = '' for i in range(n): s1 = str(random.randint(0,9)) s2 = chr(random.randint(65,90)) res += random.choice([s1,s2]) # ��������������� return res # ������ def check(self): while True: code = input('������������������>>>').strip() if code.upper() == self.cache: print('���������������������') self.t.cancel() breakobj = Code()obj.check()# ���������������IFI4������������������>>>PRC0PRCO878M������������������>>>878M���������������������
������Queue
���������������������������������������������������������������������������������������������������
���������������������
- ���������������������
- ���������������������
- ������������������������������������������������������������
���������������������������
���������������������
# ������queue-->������import queueq = queue.Queue(3) # ���������������3q.put('first')q.put(2)q.put('third')# ������print(q.get())print(q.get())print(q.get())# ���������������first2third
���������������������
# ������queue-->������import queueq = queue.LifoQueue(3)q.put(1)q.put(2)q.put(3)print(q.get())print(q.get())print(q.get())# ���������������321
������������������������������������������������������������
# ������queue-->���������import queueq = queue.PriorityQueue(3)q.put((10,'first')) # 10 ���������������q.put((40,2))q.put((20,'third'))print(q.get()) # ���������������������������print(q.get())print(q.get())# ���������������(10, 'first')(20, 'third')(40, 2)
���������������������
������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
������
���������https://docs.python.org/dev/library/concurrent.futures.htmlconcurrent.futures ������������������������������������������������ThreadPoolExecutor ������������������������������ProcessPoolExecutor ������������������������������Both implement the same interface, which is defined by the abstract Executor class.������������������������������������Executor���������������������
������������
1.submit(fn,*args,**kwargs)������������������2.map(func,*iterables,timeout=None,chunksize=1)������for������submit������3.shutdown(wait=True)���������������������pool.close()+pool.join()������wait=True���������������������������������������������������������������wait=False���������������������������������������������������������������������������wait������������������������������������������������������������������submit���map���������shutdown������4.result(timeout=None)������������ 5.add_done_callbakc(n)������������
���������
������
from concurrent.futures import ProcessPoolExecutorimport os,time, randomdef task(name): print('name:%s pid:%s'%(name,os.getpid())) time.sleep(random.randint(1,3))if __name__ == '__main__': pool = ProcessPoolExecutor(4) # ������������������������������������cpu��������� for i in range(10): pool.submit(task,'���������%s'%i) # ������������������������������������������������������ # ���������������������������10���������������������������������1��� pool.shutdown(wait=True) print('���������')
���������������������������������������������������������������������������PID���������4������������������������������PID
���������
������
from concurrent.futures import ThreadPoolExecutorimport os,time,randomdef task(name): print('name:%s pid:%s'%(name,os.getpid())) time.sleep(random.randint(0.01-0.02))if __name__ == '__main__': start_time = time.time() pool = ThreadPoolExecutor(4) for i in range(10000): pool.submit(task,'���������%s'%i) pool.shutdown(wait=True) stop_time = time.time() print('���������',stop_time-start_time)
���������������������
# ���������������������from concurrent.futures import ThreadPoolExecutorimport time,random,osfrom threading import current_threaddef task(): print('name:%s pid:%s'%(current_thread().getName(),os.getpid())) time.sleep(random.randint(1,3))if __name__ == '__main__': pool = ThreadPoolExecutor(max_workers=4) for i in range(100): pool.submit(task,) pool.shutdown(wait=True) print('���������')
map������
map(func,*iterables,timeout=None,chunksize=1) ������for������submit������
# map������from concurrent.futures import ThreadPoolExecutorimport time,osfrom threading import current_threaddef task(): print('name:%s pid:%s'%(current_thread().getName(),os.getpid())) time.sleep(1)if __name__ == '__main__': pool = ThreadPoolExecutor(max_workers=4) pool.map(task,range(1,12))
������������
������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
from concurrent.futures import ThreadPoolExecutorimport requestsimport osdef get_page(url): print('<������%s> get %s' %(os.getpid(),url)) respone=requests.get(url) if respone.status_code == 200: return {'url':url,'text':respone.text}def parse_page(res): res=res.result() print('<������%s> parse %s' %(os.getpid(),res['url'])) parse_res='url:<%s> size:[%s]\n' %(res['url'],len(res['text'])) with open('db.txt','a') as f: f.write(parse_res)if __name__ == '__main__': urls=[ 'https://www.baidu.com', 'https://www.python.org', 'https://www.openstack.org', 'https://help.github.com/', 'http://www.sina.com.cn/' ] p=ProcessPoolExecutor(3) for url in urls: p.submit(get_page,url).add_done_callback(parse_page) # parse_page������������������futuer���������������obj,result()������������ # ���������������<������2392> get https://www.baidu.com<������13288> get https://www.python.org<������1268> get https://www.openstack.org<������2392> get https://help.github.com/<������13984> parse https://www.baidu.com<������1268> get http://www.sina.com.cn/<������13984> parse https://www.openstack.org<������13984> parse http://www.sina.com.cn/<������13984> parse https://www.python.org<������13984> parse https://help.github.com/
���������������������������
- ���������������������������������������������������������������������������������������������������������������������������
- ���������������������������������������������������������������
������������������������������������������������
# ������������from concurrent.futures import ThreadPoolExecutorimport time,randomdef la(name): print('%s is laing'%name) time.sleep(random.randint(3,5)) res = random.randint(7,13)*'#' return {'name':name,'res':res}def weight(shit): name = shit['name'] size = len(shit['res']) print('%s ������ %s kg'%(name,size))if __name__ == '__main__': pool = ThreadPoolExecutor(13) shit1 = pool.submit(la,'������').result() weight(shit1) shit2 = pool.submit(la,'������').result() weight(shit2) shit3 = pool.submit(la,'���������').result() weight(shit3) # ������������������ is laing������ ������ 9 kg������ is laing������ ������ 7 kg��������� is laing��������� ������ 9 kg
# ������������from concurrent.futures import ThreadPoolExecutorimport time,randomdef la(name): print('%s is laing'%name) time.sleep(random.randint(3,5)) res = random.randint(7,13)*'#' return {'name':name,'res':res}def weight(shit): shit = shit.result() # ������������������ name = shit['name'] res = len(shit['res']) print('%s ������ %s kg'%(name,res))if __name__ == '__main__': pool = ThreadPoolExecutor(13) pool.submit(la,'������').add_done_callback(weight) # ���������������������������������������������������������return���������������futuer������������������������������������weight������ pool.submit(la,'������').add_done_callback(weight) pool.submit(la,'���������').add_done_callback(weight)# ������������������ is laing������ is laing��������� is laing��������� ������ 12 kg������ ������ 12 kg������ ������ 11 kg
发表评论
最新留言
关于作者
