classmyThread(threading.Thread): def__init__(self): threading.Thread.__init__(self) defrun(self): global x lock.acquire() # 上锁, 没开锁之前,会阻塞其他线程,直到开锁 for i inrange(3): x += i time.sleep(2) print(x) lock.release() # 开锁
lock = threading.RLock() t1 = [] for i inrange(5): t = myThread() t1.append(t) x = 0 for i in t1: i.start()
classProducer(threading.Thread): def__init__(self, threadName): threading.Thread.__init__(self, name=threadName) defrun(self): global x con.acquire() # 类似上锁 if x == 20: con.wait() print('Producer: ', end='') for i inrange(20): print(x, end=' ') x = x + 1 print(x) con.notify() # 唤醒在等待的单个线程 con.release() # 类似开锁
classConsumer(threading.Thread): def__init__(self, threadName): threading.Thread.__init__(self, name=threadName) defrun(self): global x con.acquire() if x == 0: con.wait() print('Consumer: ', end=' ') for i inrange(20): print(x, end=' ') x = x - 1 print(x) con.notify() con.release()
con = threading.Condition() x = 0 p = Producer('Producer') c = Consumer('Consumer') p.start() c.start() p.join() c.join() print('After Producer and Consumer all done: ', x)
words = {'how are you' : 'Fine, thank you.', 'how old are you?' : '21', 'what is your name?' : 'czh', "what's your name?" : 'CZH', 'where do you work?' : 'Shenzhen', 'bye': 'bye'}
HOST = '' PORT = 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1) print('Listening at port: ', PORT) conn, addr = s.accept() print('Connected by ', addr) whileTrue: data = conn.recv(1024).decode() ifnot data: break print('Received message: ', data) conn.sendall(words.get(data, 'Nothing').encode())
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((HOST, PORT)) except Exception as e: print('Server not found or not open') sys.exit() while True: c = input('输入要发送的信息: ') s.sendall(c.encode()) data = s.recv(1024).decode() print('Received: ', data) if c.lower() == 'bye': break s.close()