4.2 - 并发编程 - 线程练习题

1.基于多线程实现并发的套接字通信
server:
 1 # -*- coding:utf-8 -*-
 2 """基于多线程实现并发的套接字通信"""
 3 """有一个致命的问题,不能无限的开线程,机器会卡死了"""
 4 import socket
 5 from threading import Thread
 6 
 7 def task(conn):
 8     while True:
 9         try:
10             data = conn.recv(1024)
11             if not data: continue
12             conn.send(data.upper())
13         except Exception:
14             break
15     conn.close()
16 
17 def server(ip,port):
18     server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
19     server.bind((ip,port))
20     server.listen(5)
21     while True:
22         conn,addr = server.accept()
23         t = Thread(target=task,args=(conn,))
24         t.start()
25     server.close()
26 
27 if __name__ == "__main__":
28     server('127.0.0.1',8080)
29 
30 """应该将线程控制在一定的数量"""
31 """
32 进程池:。。。 io阻塞不用进程池了
33 线程池:。。。
34 """
35 """基于线程池实现:"""
36 import socket
37 from threading import Thread,Semaphore
38 from concurrent.futures import ThreadPoolExecutor
39 
40 def task(conn):
41     # sm.acquire()
42     while True:
43         try:
44             data = conn.recv(1024)
45             if not data: break
46             conn.send(data.upper())
47         except Exception:
48             break
49     conn.close()
50     # sm.release()
51 
52 def server(ip,port):
53     server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
54     server.bind((ip,port))
55     server.listen(5)
56     while True:
57         conn,addr = server.accept()
58         pool.submit(task,conn)
59         # t = Thread(target=task, args=(conn,))
60         # t.start()
61     server.close()
62 
63 
64 if __name__ == "__main__":
65     pool = ThreadPoolExecutor(2)  # 随着机器性能不同而不同  一般用 线程池 不用 信号量
66     # sm = Semaphore(2)
67     server('127.0.0.1',8080)
client:
 1 import socket
 2 
 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     client.send(msg.encode('utf-8'))
 9     data = client.recv(1024)
10     print(data.decode('utf-8'))
2.编写一个简单的文本处理工具,具备三个任务,一个接收用户输入,一个将用户输入的内容格式化成大写,一个将格式化后的结果存入文件
 1 from threading import Thread
 2 import json
 3 import time
 4 
 5 def save(msg_upper):
 6     with open('db.txt','a',encoding='utf-8') as f:
 7         json.dump(msg_upper,f)
 8 
 9 def handle(msg):
10     time.sleep(10)
11     msg_upper = msg.upper()
12     p2 = Thread(target=save,args=(msg_upper,))
13     p2.start()
14 
15 def recv():
16     while True:
17         msg = input('>>>:').strip()
18         p1 = Thread(target=handle, args=(msg,))
19         p1.start()
20 
21 if __name__ == "__main__":
22     recv()



posted @ 2018-04-03 15:23  Alice的小屋  阅读(220)  评论(0编辑  收藏  举报