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]app
使用互斥鎖解決資源競爭的問題socket
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()