欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python学习之多任务②

程序员文章站 2022-05-27 09:47:29
...

线程共享全局变量

import threading

# 定义全局变量 globals_num
globals_num = 0


def test1(num):
    global globals_num
    for i in range(num):
        globals_num += 1
    print("test1当前变量值为:%d" % globals_num)


def test2(num):
    global globals_num
    for i in range(num):
        globals_num+=1
    print("test2当前变量值为:%d" % globals_num)



def main():
    print("最开始的g_num = %d "%globals_num)
    t1 = threading.Thread(target=test1,args=(100,))
    t2 = threading.Thread(target=test2,args=(100,))
    t1.start()
    t2.start()


if __name__ == '__main__':
    main()

线程互斥锁

import threading
import time

g_num = 0

def test1(num):
    global g_num
    for i in range(num):
        mutex.acquire()  # 上锁
        g_num += 1
        mutex.release()  # 解锁

    print("---test1---g_num=%d"%g_num)

def test2(num):
    global g_num
    for i in range(num):
        mutex.acquire()  # 上锁
        g_num += 1
        mutex.release()  # 解锁

    print("---test2---g_num=%d"%g_num)

# 创建一个互斥锁
# 默认是未上锁的状态
mutex = threading.Lock()

# 创建2个线程,让他们各自对g_num加1000000次
p1 = threading.Thread(target=test1, args=(1000000,))
p1.start()

p2 = threading.Thread(target=test2, args=(1000000,))
p2.start()

# 等待计算完成
while len(threading.enumerate()) != 1:
    time.sleep(1)

print("2个线程对同一个全局变量操作之后的最终结果是:%s" % g_num)

多任务udp聊天

import socket
import threading

def send_msg(udp_socket):
    while True:
        # 输入ip
        dest_ip = input("请输入ip:")
        # 输入port
        dest_port = int(input("请输入port:"))
        dest_data = (dest_ip,dest_port)

        # 发送数据
        data = input("请输入你要发送的东西:")
        udp_socket.sendto(data.encode("gbk"),dest_data)

def reve_msg(udp_socket):
    while True:
        reve_data = udp_socket.recvfrom(1024)
        reve_ip = reve_data[1]
        reve_need_data = reve_data[0].decode("gbk")
        print("%s收到的数据是:%s"%(reve_ip,reve_need_data))



def main():
    # 创建套接字
    udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    # 绑定端口
    udp_socket.bind(("",8080))


    # 创建线程
    send_2_mes = threading.Thread(target=send_msg,args=(udp_socket,))
    reve_2_msg = threading.Thread(target=reve_msg,args=(udp_socket,))
    send_2_mes.start()
    reve_2_msg.start()




if __name__ == '__main__':
    main()
相关标签: python学习