线程

2020-03-06  本文已影响0人  GaoYuan117

1. 使用threading模块

示例代码:

import time
import threading

# 线程共享全局变量
g_num = 10

g_nums = [1, 2]


def sing():
    global g_num
    g_num += 1
    for i in range(5):
        print("唱歌~")
        time.sleep(1)


def dance(temp):
    temp.append(21)
    for i in range(5):
        print("跳舞~")
        time.sleep(1)


# 创建子线程,方法不要带()
# target指定调用哪个线程
# args 指定调用函数的时候传递什么参数过去,只有一个参数的时候也要(g_nums,)
t1 = threading.Thread(target=sing)
t2 = threading.Thread(target=dance, args=(g_nums,))

# 启动线程
# 线程的运行没有先后顺序
t1.start()
t2.start()

print(g_num)
print(g_nums)

# 查看线程个数
print(threading.enumerate())

总结

  1. 当调用start()时,才会真正的创建线程,并且开始执行
  2. 主线程会等待所有的子线程结束后才结束
  3. 查看线程个数使用threading.enumerate()

2. 线程执行代码的封装

通过使用threading模块能完成多任务的程序开发,为了让每个线程的封装性更完美,所以使用threading模块时,往往会定义一个新的子类class,只要继承threading.Thread就可以了,然后重写run方法

示例如下:

#coding=utf-8
import threading
import time

class MyThread(threading.Thread):
    def run(self):
        for i in range(3):
            time.sleep(1)
            msg = "I'm "+self.name+' @ '+str(i) #name属性中保存的是当前线程的名字
            print(msg)

if __name__ == '__main__':
    t = MyThread()
    t.start()

总结

3. 线程的执行顺序

#coding=utf-8
import threading
import time

class MyThread(threading.Thread):
    def run(self):
        for i in range(3):
            time.sleep(1)
            msg = "I'm "+self.name+' @ '+str(i)
            print(msg)
def test():
    for i in range(5):
        t = MyThread()
        t.start()
if __name__ == '__main__':
    test()

执行结果:(运行的结果可能不一样,但是大体是一致的)

    I'm Thread-1 @ 0
    I'm Thread-2 @ 0
    I'm Thread-5 @ 0
    I'm Thread-3 @ 0
    I'm Thread-4 @ 0
    I'm Thread-3 @ 1
    I'm Thread-4 @ 1
    I'm Thread-5 @ 1
    I'm Thread-1 @ 1
    I'm Thread-2 @ 1
    I'm Thread-4 @ 2
    I'm Thread-5 @ 2
    I'm Thread-2 @ 2
    I'm Thread-1 @ 2
    I'm Thread-3 @ 2

总结

4. 多线程-共享全局变量


from threading import Thread
import time

g_num = 100

def work1():
    global g_num
    for i in range(3):
        g_num += 1

    print("----in work1, g_num is %d---"%g_num)

def work2():
    global g_num
    print("----in work2, g_num is %d---"%g_num)

print("---线程创建之前g_num is %d---"%g_num)

t1 = Thread(target=work1)
t1.start()

#延时一会,保证t1线程中的事情做完
time.sleep(1)

t2 = Thread(target=work2)
t2.start()

运行结果:

---线程创建之前g_num is 100---
----in work1, g_num is 103---
----in work2, g_num is 103---

列表当做实参传递到线程中

from threading import Thread
import time

def work1(nums):
    nums.append(44)
    print("----in work1---",nums)

def work2(nums):
    #延时一会,保证t1线程中的事情做完
    time.sleep(1)
    print("----in work2---",nums)

g_nums = [11,22,33]

t1 = Thread(target=work1, args=(g_nums,))
t1.start()

t2 = Thread(target=work2, args=(g_nums,))
t2.start()

运行结果:

----in work1--- [11, 22, 33, 44]
----in work2--- [11, 22, 33, 44]

总结:

5. 互斥锁

threading模块中定义了Lock类,可以方便的处理锁定:

# 创建锁
mutex = threading.Lock()

# 锁定
mutex.acquire()

# 释放
mutex.release()

注意:

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)

运行结果:

---test1---g_num=1909909
---test2---g_num=2000000
2个线程对同一个全局变量操作之后的最终结果是:2000000

可以看到最后的结果,加入互斥锁后,其结果与预期相符。

总结

6. 多任务版udp聊天器

客户端1:

# -*- coding:utf-8 -*-
# Author GaoYuan

import socket
import threading

udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

udp_socket.bind(("192.168.1.118", 8891))


def send_data():
    """发送数据"""
    while True:
        content = input()
        udp_socket.sendto(content.encode("utf-8"), ("192.168.1.118", 8892))


def recv_data():
    """接收数据"""
    while True:
        recv_data = udp_socket.recvfrom(1024)
        print(recv_data)


threading.Thread(target=send_data).start()
threading.Thread(target=recv_data).start()

客户端2:

# -*- coding:utf-8 -*-
# Author GaoYuan

import socket
import threading

udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

udp_socket.bind(("", 8892))


def send_data():
    """发送数据"""
    while True:
        content = input()
        udp_socket.sendto(content.encode("utf-8"), ("192.168.1.118", 8891))


def recv_data():
    """接收数据"""
    while True:
        recv_data = udp_socket.recvfrom(1024)
        print(recv_data)


threading.Thread(target=send_data).start()
threading.Thread(target=recv_data).start()
上一篇下一篇

猜你喜欢

热点阅读