import time import threading # 定义一个全局变量 def test(temp): temp.append(33) print("---in test g_num=%s" % str(temp)) def test2(temp): print("---in test2 g_num=%s" % str(temp)) g_nums = [11, 22] def main(): # target 指定将来这个线程去哪个函数执行代码 # args 指定将来调用函数的时候传递什么数据过去 t1 = threading.Thread(target=test, args=(g_nums,)) t2 = threading.Thread(target=test2, args=(g_nums,)) t1.start() time.sleep(1) t2.start() print("---in thread g_num=%s" % str(g_nums)) if __name__ == "__main__": main()
---in test g_num=[11, 22, 33]
---in test2 g_num=[11, 22, 33]
---in thread g_num=[11, 22, 33]
使用互斥锁解决资源竞争的问题
import socket import threading def recv_msg(udp_socket): # 收到数据 while True: recv_data = udp_socket.recvfrom(1024) print(recv_data) def send_msg(udp_socket, dest_ip, dest_port): # 发送数据 while True: send_data = input("输入要发送的数据") udp_socket.sendto(send_data.encode("gbk"), (dest_ip, dest_port)) def main(): """完成udp聊天器的整体控制""" # 1 创建套接字 udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 2 绑定端口 udp_socket.bind(("",7890)) # 3 获取对方的IP dest_ip = input("IP") dest_port = int(input("port")) # 4 创建两个进程执行相应的功能 t1 = threading.Thread(target=recv_msg, args=(udp_socket,)) t2 = threading.Thread(target=send_msg, args=(udp_socket, dest_ip, dest_port,)) t1.start() t2.start() if __name__ == "__main__": main()