1. 程式人生 > >5.1.22 多線程實現並發

5.1.22 多線程實現並發

AS bre sed 服務器 executor tin 多線程 pan class

服務器端:

from socket import *
from threading import Thread

def communicate(conn):
    while True:
        try:
            data=conn.recv(1024)
            if not data:break
            conn.send(data.upper())
        except ConnectionResetError:
            break

    conn.close()

def server(ip,port):
    server 
= socket(AF_INET, SOCK_STREAM) server.bind((ip,port)) server.listen(5) while True: conn, addr = server.accept() t=Thread(target=communicate,args=(conn,)) t.start() server.close() if __name__ == __main__: server(127.0.0.1, 8081)

客戶端:

from socket import
* client=socket(AF_INET,SOCK_STREAM) client.connect((127.0.0.1,8081)) while True: msg=input(>>: ).strip() if not msg:continue client.send(msg.encode(utf-8)) data=client.recv(1024) print(data.decode(utf-8)) client.close()

該種實現有什麽弊端嗎?

如果有10萬個客戶端,就得開10萬個線程?單臺服務器支撐得了不?

進程池或線程池實現並發:

from concurrent.futures import ThreadPoolExecutor
from threading import current_thread
import time


def work(n):
    print(n, ======, current_thread().getName())
    time.sleep(1)


if __name__ == __main__:
    pool = ThreadPoolExecutor(3, thread_name_prefix=pool_)   # 3 是線程池大小

    for i in range(10):   # 任務數
        pool.submit(work, i)   # 單個任務提交到線程池中   def submit(self, fn, *args, **kwargs):
   # pool.shutdown(wait=False)   # 默認是wait=False 不等任務執行結果,就執行主線程接下來的代碼
print(主線程。。。。。)

運行結果:

技術分享圖片
0 ====== pool__0
1 ====== pool__1
2 ====== pool__2
主線程。。。。。
3 ====== pool__0
4 ====== pool__1
5 ====== pool__2
6 ====== pool__1
7 ====== pool__2
8 ====== pool__0
9 ====== pool__2
View Code

如何做到線程的join效果呢?等任務都執行完後,才執行主程序代碼。

from concurrent.futures import ThreadPoolExecutor
from threading import current_thread
import time


def work(n):
    print(n, ======, current_thread().getName())
    time.sleep(1)


if __name__ == __main__:
    pool = ThreadPoolExecutor(3, thread_name_prefix=pool_)

    for i in range(10):
        pool.submit(work, i)

    pool.shutdown(wait=True)   # 相當於join的功能。 實際原理是:斷開新任務進到線程池中,等待池中的任務執行完。
    # pool.shutdown(wait=False)   # 默認是wait=False 不等任務執行結果,就執行主線程接下來的代碼 
    print(主線程。。。。。)

運行結果:

技術分享圖片
0 ====== pool__0
1 ====== pool__1
2 ====== pool__2
3 ====== pool__1
4 ====== pool__0
5 ====== pool__2
6 ====== pool__1
7 ====== pool__0
8 ====== pool__2
9 ====== pool__1
主線程。。。。。
View Code

5.1.22 多線程實現並發