简单实现多线程
import threading import time def sing(sing): for i in range(5): print("---sing()---{}".format(sing)) time.sleep(1) def dance(dance): for i in range(5): print("---dance()---{}".format(dance)) time.sleep(1) def main(): t1 = threading.Thread(target=sing,args=("t1",)) t2 = threading.Thread(target=dance,args=("t2",)) t1.start() t2.start() if __name__ == "__main__": main()
多线程互斥锁
import threading import time A = 2 lock = threading.Lock() #创建一个互斥锁 def sing(sing): global A for i in range(500000): lock.acquire() #加锁 A += 1 lock.release() #解锁 print('{}:{}'.format(sing,i)) def dance(dance): global A for i in range(500000): lock.acquire() #加锁 A -= 1 lock.release() #解锁 print('{}:{}'.format(dance,i)) def main(): global A t1 = threading.Thread(target=sing,args=("t1",)) t2 = threading.Thread(target=dance,args=("t2",)) t1.start() t2.start() t1.join() t2.join() print(A) if __name__ == "__main__": main()
查看线程数量
使用
threading.enumerate()
获取当前所有线程。
此处打印出一个列表,列表中共有3个线程信息。一个是主线程,另外两个是子线程
这里需要注意,我们需要在代码中使用join()方法来阻塞主线程。当所有阻塞的子线程执行完毕后,才会继续执行主线程。
通过继承Thread类,重写run方法实现多线程
import threading import time A = 2 lock = threading.Lock() #创建一个互斥锁 class my_thread(threading.Thread): def run(self) -> None: self.sing() def sing(self): global A if self._kwargs['mothed'] == 'add': tmp = 1 elif self._kwargs['mothed'] == 'del': tmp = -1 else: tmp = 1 for i in range(50): lock.acquire() #加锁 A += tmp lock.release() #解锁 print('{}:{}:{}'.format(self._kwargs['cs'],i,A)) def main(): global A t1 = my_thread(kwargs={'cs':'sing','mothed':'add'},name="T1") t2 = my_thread(kwargs={'cs':'dance','mothed':'del'},name="T2") t1.start() t2.start() print(threading.enumerate()) print(A) t1.join() t2.join() print(A) if __name__ == "__main__": main()
多线程UDP聊天器
import threading import socket class my_thread(threading.Thread): def run(self) -> None: if self._kwargs['mothed'] == 'recv_message': self.recv_message() elif self._kwargs['mothed'] == 'send_message': self.send_message() def send_message(self): while True: try: ip = input("目标IP:") port = int(input("目标端口:")) msg = input("发送的消息:").encode('utf-8') except: continue self._kwargs['udp_socket'].sendto(msg,(ip,port)) def recv_message(self): while True: data,client_addr = self._kwargs['udp_socket'].recvfrom(1024) print('source:', client_addr,'收到的数据:', data.decode("UTF-8")) def main(): udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) udp_socket.bind(("",20216)) recv_message = my_thread(kwargs={'udp_socket':udp_socket,'mothed':'recv_message'},name="recv_message") send_message = my_thread(kwargs={'udp_socket':udp_socket,'mothed':'send_message'},name="send_message") recv_message.start() send_message.start() recv_message.join() send_message.join() if __name__ == "__main__": main()