5.1.22 多线程实现并发

服务器端:

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

猜你喜欢

转载自www.cnblogs.com/beallaliu/p/9192343.html