Python--day40--全局解释器锁

 

1,起一百个线程和起一百个进程所花的时间对比(开启效率的较量):

 1 import time
 2 from threading import Thread
 3 from multiprocessing import Process
 4 
 5 def func(n):
 6     n+1
 7 
 8 if __name__ == '__main__':
 9     start = time.time()
10     t_lst = []
11     for i in range(100):
12         t = Thread(target=func,args=(i,))
13         t.start()
14         t_lst.append(t)
15     for t in t_lst:t.join()
16     t1 = time.time() -start
17 
18     start = time.time()
19     t_lst = []
20     for i in range(100):
21         t = Process(target=func, args=(i,))
22         t.start()
23         t_lst.append(t)
24     for t in t_lst: t.join()
25     t2 = time.time() - start
26     print(t1,t2)

运行结果:

2,多线程可以写input

3,socketserver聊天的例子:

server.py

 1 import socket
 2 from threading import Thread
 3 
 4 def chat(conn):
 5     conn.send(b'hello')
 6     msg = conn.recv(1024).decode('utf-8')
 7     print(msg)
 8     conn.close()
 9 
10 sk = socket.socket()
11 sk.bind(('127.0.0.1',8080))
12 sk.listen()
13 
14 while True:
15     conn,addr = sk.accept()
16     t = Thread(target=chat,args=(conn,)).start()
17 
18 sk.close()

client.py

 1 import socket
 2 
 3 sk = socket.socket()
 4 sk.connect(('127.0.0.1',8080))
 5 
 6 msg = sk.recv(1024)
 7 print(msg)
 8 inp = input('>>>').encode('utf-8')
 9 sk.send(inp)
10 sk.close()

运行结果:

 

posted @ 2019-01-31 21:03  莱茵河的雨季  阅读(150)  评论(0编辑  收藏  举报