Python 线程模块快速指南及示例

王林
发布: 2024-09-12 14:17:31
原创
515 人浏览过

A Quick Guide to the Python threading Module with Examples

介绍

Python 中的线程模块提供了一个高级接口来创建和管理线程,使您能够并发运行代码。这对于可以并行执行的任务(例如 I/O 密集型操作)特别有用。下面列出了 threading 模块中常用的方法和函数,并附有简短的示例。

1. 线程()

Thread 类是线程模块的核心。您可以使用此类创建和启动新线程。

import threading

def print_numbers():
    for i in range(5):
        print(i)

t = threading.Thread(target=print_numbers)
t.start()  # Starts a new thread
t.join()   # Waits for the thread to finish
登录后复制

2. 开始()

启动线程的活动。

t = threading.Thread(target=print_numbers)
t.start()  # Runs the target function in a separate thread
登录后复制

3. 加入([超时])

阻塞调用线程,直到调用 join() 方法的线程终止。您可以选择指定超时。

t = threading.Thread(target=print_numbers)
t.start()
t.join(2)  # Waits up to 2 seconds for the thread to finish
登录后复制

4.is_alive()

如果线程仍在运行,则返回 True。

t = threading.Thread(target=print_numbers)
t.start()
print(t.is_alive())  # True if the thread is still running
登录后复制

5. 当前线程()

返回当前Thread对象,代表调用线程。

import threading

def print_current_thread():
    print(threading.current_thread())

t = threading.Thread(target=print_current_thread)
t.start()  # Prints the current thread info
登录后复制

6. 枚举()

返回当前活动的所有 Thread 对象的列表。

t1 = threading.Thread(target=print_numbers)
t2 = threading.Thread(target=print_numbers)
t1.start()
t2.start()

print(threading.enumerate())  # Lists all active threads
登录后复制

7. 活动计数()

返回当前存活的Thread对象的数量。

print(threading.active_count())  # Returns the number of active threads
登录后复制

8. 锁定()

Lock 对象是一个原始锁,用于防止竞争条件。您可以使用它来确保一次只有一个线程访问共享资源。

lock = threading.Lock()

def thread_safe_function():
    with lock:  # Acquires the lock
        # Critical section
        print("Thread-safe code")

t = threading.Thread(target=thread_safe_function)
t.start()
登录后复制

9. RLock()

可重入锁允许线程多次 acquire() 锁,而不会阻塞自身。

lock = threading.RLock()

def reentrant_function():
    with lock:
        with lock:  # Same thread can acquire the lock again
            print("Reentrant lock example")

t = threading.Thread(target=reentrant_function)
t.start()
登录后复制

10. 条件()

Condition 对象允许线程等待满足某些条件。

condition = threading.Condition()

def thread_wait():
    with condition:
        condition.wait()  # Wait for the condition
        print("Condition met")

def thread_notify():
    with condition:
        condition.notify()  # Notify the waiting thread

t1 = threading.Thread(target=thread_wait)
t2 = threading.Thread(target=thread_notify)
t1.start()
t2.start()
登录后复制

11. 事件()

Event 对象用于在线程之间发出信号。一个线程可以等待事件被设置,另一个线程可以设置事件。

event = threading.Event()

def wait_for_event():
    event.wait()  # Wait until the event is set
    print("Event has been set")

t = threading.Thread(target=wait_for_event)
t.start()
event.set()  # Set the event to allow the thread to continue
登录后复制

12. 信号量()

信号量对象允许您限制可以同时访问资源的线程数量。

semaphore = threading.Semaphore(2)  # Only 2 threads can access the resource at once

def access_resource():
    with semaphore:
        print("Resource accessed")

t1 = threading.Thread(target=access_resource)
t2 = threading.Thread(target=access_resource)
t3 = threading.Thread(target=access_resource)

t1.start()
t2.start()
t3.start()
登录后复制

13.定时器(间隔、函数)

定时器线程在指定的时间间隔后执行函数。

def delayed_function():
    print("Executed after delay")

timer = threading.Timer(3, delayed_function)
timer.start()  # Executes `delayed_function` after 3 seconds
登录后复制

14. setDaemon(真)

守护线程在后台运行,并在主程序退出时自动退出。您可以通过调用 setDaemon(True) 或将 daemon=True 传递给 Thread 构造函数来使线程成为守护进程。

t = threading.Thread(target=print_numbers, daemon=True)
t.start()  # Daemon thread will exit when the main program ends
登录后复制

结论

threading 模块是 Python 中处理并发的强大工具。它提供了多个类和方法来创建和控制线程,从而可以轻松并行执行代码。从使用基本的 Thread 对象到使用 Lock 和 Semaphore 管理同步,该模块对于编写并发 Python 程序至关重要。

以上是Python 线程模块快速指南及示例的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!