线程池,协程

 

线程的其他方法: 

  Threading.current_thread() #当前线程对象
  GetName() 获取线程名
  Ident 获取线程id
  Threading.Enumerate() #当前正在运行的线程对象的一个列表
  Threading.active_count() #当前正在运行的线程数量

  

 1 import time
 2 import threading
 3 from threading import Thread,current_thread
 4 def fn(n):
 5     time.sleep(1)
 6     print('子线程名称:',current_thread().getName())
 7     print('%s线程任务'%n)
 8 def f2(n):
 9     time.sleep(1)
10     print('子线程名称:',current_thread().getName())
11     print('%s线程任务'%n)
12 if __name__ == '__main__':
13     t1 = Thread(target=fn,args=(1,))
14     t2 = Thread(target=f2,args=(2,))
15     t1.start()
16     t2.start()
17     print('主线程名称:',current_thread().getName())
18     print('主线程ID:',current_thread().ident)
19     print(current_thread())
20     print(threading.enumerate())
21     print(threading.active_count())

 

线程队列:

种类:
  Import queue
  先进先出队列:queue.Queue(3)
  先进后出\后进先出队列:queue.LifoQueue(3)
  优先级队列:queue.priorityQueue(3)   Put的数据是一个元组,元组的第一个参数是优先级数字,数字越小优先级越高,
                    越先被get到被取出来,第二个参数是put进去的值,如果说优先级相同,那么值别忘了
                    应该是相同的数据类型,字典不行

方法:
  q.put() 进
  q.put_nowait()不阻塞的进,超出队列长度会报错 Exception
  q.qsize() 查看当前队列长度
  q.full() 查看当前队列是否满了,返回True或返回False

  q.get() 取
  q.get_nowait() 不阻塞的取,超出队列长度会报错 Exception
  q.empty() 查看当前队列是否空了,返回True或返回False

 1 import queue
 2 q = queue.Queue(4)
 3 q.put(1)
 4 q.put(2)
 5 q.put(3)
 6 print(q.qsize())
 7 q.put(4)
 8 print(q.full())
 9 try:
10     q.put_nowait(1)
11 except Exception:
12     print('队列满了')
13 print(q.get())
14 print(q.get())
15 print(q.get())
16 print(q.get())
17 print(q.empty())
18 try:
19     q.get_nowait()
20 except Exception:
21     print('队列空了')
22 
23 import queue
24 q = queue.LifoQueue(4)
25 q.put(1)
26 q.put(2)
27 q.put(3)
28 q.put(4)
29 print(q.get())
30 print(q.get())
31 print(q.get())
32 print(q.get())
33 
34 import queue
35 q = queue.PriorityQueue(3)
36 q.put((3,'123'))
37 q.put((5,[1,2,3]))
38 q.put((8,(1,2,3,)))
39 print(q.get())
40 print(q.get())
41 print(q.get())

 

线程池:

  submit #异步提交任务
  result #和get方法一样,如果没有结果,会等待,阻塞程序
  shutdown #主线程等待所有提交给线程池的任务,全部执行完毕 close + join

 1 import time
 2 from threading import current_thread
 3 from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
 4 def ft(a,b):
 5     time.sleep(1)
 6     print('%s号子线程'%current_thread().ident)
 7     return a,b
 8 def fp(c,d):
 9     time.sleep(1)
10     print('%s号子进程'%current_thread().ident)
11     return c,d
12 if __name__ == '__main__':
13     t = ThreadPoolExecutor(4)
14     p = ProcessPoolExecutor(4)
15     res_list = []
16     for i in range(10):
17         res = t.submit(ft,i,'why')
18         res_list.append(res)
19     print([r.result() for r in res_list])
20 
21     ret_list = []
22     for el in range(10):
23         ret = p.submit(fp,el,'www')
24         ret_list.append(ret)
25     print([p.result() for p in ret_list])
26     t.shutdown()     #主线程等待所有提交给线程池的任务,全部执行完毕 close + join
27     p.shutdown()     #主线程等待所有提交给线程池的任务,全部执行完毕 close + join
28     print('主线程结束')
29     print('主进程结束')

 

线程池回调函数: from conncurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor

1 from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
2 def f1(n,s):
3     return n + s
4 def f2(n):
5     print('回调函数>>>',n.result())
6 if __name__ == '__main__':
7     t = ThreadPoolExecutor(4)  #这里可以更改为ProcessPoolExecutor使用
8     res = t.submit(f1,11,12).add_done_callback(f2)   #将f1中的值回调给f2    

 

多线程实现socket

 1 #服务端
 2 import threading
 3 import socket
 4 server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 5 server.bind(('127.0.0.1',8080))
 6 server.listen(5)
 7 def action(conn):
 8     while True:
 9         data=conn.recv(1024)
10         print(data.decode('utf-8'))
11         msg = input('服务端输入:') #在多线程里面可以使用input输入内容,那么就可以实现客户端和服务端的聊天了,多进程不能输入
12         conn.send(msg.encode('utf-8'))
13 
14 if __name__ == '__main__':
15 
16     while True:
17         conn,addr=server.accept()
18         p=threading.Thread(target=action,args=(conn,))
19         p.start()
 1 #客户端
 2 import socket
 3 client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 4 client.connect(('127.0.0.1',8080))
 5 while True:
 6     msg=input('>>: ').strip()
 7     if not msg:continue
 8 
 9     client.send(msg.encode('utf-8'))
10     data=client.recv(1024)
11     print(data.decode('utf-8'))

 

猜你喜欢

转载自www.cnblogs.com/Godisgirl/p/10269246.html
0条评论
添加一条新回复