Python进阶-多线程

TOC

多线程编程

多线程允许你在同一个程序中并发执行多个任务,提高程序的性能,尤其在I/O密集型操作中。

  • 线程:线程是进程中的一个执行流,是程序执行的最小单位。
  • 多线程:在同一个进程中同时执行多个线程,可以共享内存和资源。

threading库

threading模块提供了创建和管理线程的类和方法。
使用方法:

# 导入库
import threading
import time

code = 'abcde'

# 定义方法模拟耗时任务
def print_string(string):
    print(string)
    time.sleep(1)

# 创建多线程完成任务
for i in code:
    threads = []
    # 创建线程
    t = threading.Thread(target=print_string, args=(i,))
    # 开始线程
    t.start()
    # 线程任务加入列表
    threads.append(t)
    # 等待所有线程完成
    for t in threads:
        t.join()
"""
Thread             用于创建新线程。
start()            启动线程。
join()             等待线程完成。
current_thread()   获取当前线程。
active_count()     返回当前活跃线程的数量。
"""

使用实例

创建两个列表,用两个线程去分别输出两个列表

import threading  
import time  
  
# 定义2个列表  
my_list_a = [1, 2, 3, 4, 5]  
my_list_b = [6, 7, 8, 9, 10]


def print_list_a():
    for i in my_list_a:
        print(i)
        time.sleep(1)  # 模拟一些耗时操作


def print_list_b():
    for i in my_list_b:
        print(i)
        time.sleep(1)  # 模拟一些耗时操作


def run_threads():
    threads = []
    t1 = threading.Thread(target=print_list_a)
    t2 = threading.Thread(target=print_list_b)
    t1.start()
    t2.start()
    # 将线程加入到列表中
    threads.append(t1)
    threads.append(t2)
    # 等待所有线程执行完毕
    for t in threads:
        t.join()
    print("All elements have been printed.")

# 调用方法开始运行
run_threads()
# 输出结果:
"""
1
6
2
7
8
3
4
9
5
10
All elements have been printed.
"""

线程安全(锁)

  • 全局解释器锁(GIL):Python中全局解释器锁限制了同一时间只能有一个线程执行代码,这就意味着多线程早CPU密集型操作上可能不会带来性能提升,但是在I/O密集型操作中(网络请求、文件操作)中仍然表现良好。
  • 线程安全:在多个线程共享数据时,需要注意数据的同步和安全。可以使用threading.Lock来实现线程同步。
    使用方法:
import threading

# 初始化锁对象
lock = threading.Lock()
lock.acquire()
lock.release()

使用实例:
1.给输出列表加上锁,防止输出混乱

import threading
import time

code = 'abcde'
# 初始化锁对象
lock = threading.Lock()

# 定义方法模拟耗时任务
def print_string(string):
    lock.acquire()
    print(string)
    time.sleep(1)
    lock.release()

# 创建多线程完成任务
for i in code:
    threads = []
    # 创建线程
    t = threading.Thread(target=print_string, args=(i,))
    # 开始线程
    t.start()
    # 线程任务加入列表
    threads.append(t)

# 等待所有线程完成
for t in threads:
	t.join()
print("All elements have been printed.")
# 结果对比
"""
没有加锁之前,耗时1s,输出结果:
a
bc
d

e
All elements have been printed.
# 加上锁之后,耗时5s,输出结果:
a
b
c
d
e
All elements have been printed.
"""

2.当需要多线程操作共享数据的时候,也可以运用到锁来进行工作

import threading

# 共享资源
counter = 0
lock = threading.Lock()

def increment():
    global counter
    for _ in range(100):
        lock.acquire()  # 获取锁
        counter += 1
        lock.release()  # 释放锁

# 创建多个线程
threads = []
for _ in range(5):
    thread = threading.Thread(target=increment)
    threads.append(thread)
    thread.start()

# 等待所有线程完成
for thread in threads:
    thread.join()

print("Final counter value:", counter)