python基础之标准库基于线程threading模块介绍相关3

71 阅读2分钟

继续介绍如何使用 threading 模块通过类的方式创建和管理线程:

使用类创建线程

你可以通过创建一个继承自 threading.Thread 的子类来定义线程的行为。这种方式更加面向对象,允许你在线程中封装更多的功能。

import threading

class MyThread(threading.Thread):
    def __init__(self, name):
        super().__init__(name=name)

    def run(self):
        # 在这里定义线程的主要逻辑
        print(f"Thread {self.name} is running")

# 创建并启动线程
thread1 = MyThread("Thread 1")
thread2 = MyThread("Thread 2")

thread1.start()
thread2.start()

# 等待线程结束
thread1.join()
thread2.join()

print("All threads have finished")

类的线程同步

通过类创建的线程也可以使用锁和条件变量等线程同步机制来确保线程安全。例如,在类中定义一个锁属性,以便多个线程能够安全地访问共享资源。

import threading

class SharedResource:
    def __init__(self):
        self.lock = threading.Lock()
        self.value = 0

    def increment(self):
        with self.lock:
            self.value += 1

# 创建共享资源
resource = SharedResource()

def worker():
    for _ in range(100000):
        resource.increment()

# 创建多个线程来增加共享资源的值
threads = [threading.Thread(target=worker) for _ in range(4)]

for thread in threads:
    thread.start()

for thread in threads:
    thread.join()

print(f"Final value of the shared resource: {resource.value}")

类的线程同步示例

上述示例演示了如何使用类创建的线程来安全地访问共享资源。通过定义一个锁属性 self.lock,多个线程可以使用 with self.lock 来确保对 self.value 的访问是线程安全的。

注意事项

  • 当使用类创建线程时,确保在类的 run 方法中定义线程的主要逻辑。
  • 合理使用锁、条件变量等线程同步机制以确保线程安全。
  • 确保适当地管理线程的生命周期,包括启动线程、等待线程结束等操作。

通过类创建线程可以更好地封装线程的行为,使代码更模块化和可维护。这种方式特别适用于需要在多个地方使用相同线程逻辑的情况。