多线程
多线程例子, 注释部份即为多线程的使用
#-*- coding: utf-8 -*-# Wind clear raise# 2017/3/5 下午2:34import socketimport threadingimport timeimport queue, jsonimport hashlibdef list(conn): conn.send(b"list") recv_data_size = conn.recv(1024) conn.send(b"OK") recv_data_size = int(recv_data_size.decode()) recv_size = 0 res = b'' while recv_size < recv_data_size: data = conn.recv(1024) res += data recv_size += len(data) print(res.decode())def run(username, password, i): client = socket.socket() client.connect(('localhost', 9999)) sha = hashlib.sha256() sha.update(password.encode()) data = { "account_id": username, "password": sha.hexdigest()} # 服务器只返回一次 client.send(json.dumps(data).encode()) res = client.recv(1024) if res != b'Fail': print("登录成功. 服务器返回:", res.decode(), threading.current_thread(), i) # list(client) else: print("密码错误") client.close()def run2(name, paswd, i): print(i, threading.current_thread())if __name__ == "__main__": # start_time = time.time() # d = ["alex", 'alex2', "user01"] # obj_t = [] # for i in range(1000): # # for name in d: # # run(name, "123") # t = threading.Thread(target=run, args=("alex", "123", i)) # # obj_t.append(t) # t.start() # # # for t in obj_t: # # t.start() # # for t in obj_t: # # t.join() # # print("end: ", time.time() - start_time) client = socket.socket() client.connect(('localhost', 9999)) client.send(b'hello') print(client.recv(1024))
线程之间通信:queue
import queue# q = queue.Queue() # 先进先出q = queue.LifoQueue() # 后进先出q.put(1)q.put(2)q.put(3)q.put(4)print(q.get())print(q.get())print(q.get())print(q.get())q = queue.PriorityQueue()q.put((-1, "1"))q.put((10, "2"))q.put((5, "3"))print(q.get())print(q.get())print(q.get())print(q.get())