简要讲解Python编程中线程的创建与锁的使用

  
  1. Python线程创建

在Python中,创建线程有两种方式:直接创建Thread对象和继承Thread类创建线程。

直接创建Thread对象:

import threading

def func():
    print("Hello, World!")

if __name__ == "__main__":
    t = threading.Thread(target=func)
    t.start()

继承Thread类创建线程:

import threading

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

    def run(self):
        print("Hello, World!")

if __name__ == "__main__":
    t = MyThread()
    t.start()
  1. Python锁的使用

在Python中,使用锁来控制线程的访问,防止出现数据竞争和死锁。

创建锁对象:

import threading

lock = threading.Lock()

Lock类提供了两个方法,acquire()release(),分别用于获取和释放锁。

加锁:

lock.acquire()
# 访问共享变量
lock.release()

示例1:多线程访问共享变量

import threading

count = 0
lock = threading.Lock()

def increment():
    global count
    for i in range(0, 100000):
        # 加锁
        lock.acquire()
        count += 1
        # 释放锁
        lock.release()

if __name__ == "__main__":
    threads = []
    for i in range(0, 5):
        t = threading.Thread(target=increment)
        threads.append(t)
        t.start()

    for t in threads:
        t.join()

    print("count:", count)

示例2:避免死锁

import threading

lock1 = threading.Lock()
lock2 = threading.Lock()

def func1():
    lock1.acquire()
    # do something
    lock2.acquire()
    # do something
    lock2.release()
    lock1.release()

def func2():
    lock2.acquire()
    # do something
    lock1.acquire()
    # do something
    lock1.release()
    lock2.release()

if __name__ == "__main__":
    t1 = threading.Thread(target=func1)
    t2 = threading.Thread(target=func2)

    t1.start()
    t2.start()

    t1.join()
    t2.join()
相关文章