"إذا أراد العامل أن يؤدي عمله بشكل جيد، فعليه أولاً أن يشحذ أدواته." - كونفوشيوس، "مختارات كونفوشيوس. لو لينجونج"
الصفحة الأمامية > برمجة > دليل سريع لوحدة خيوط بايثون مع أمثلة

دليل سريع لوحدة خيوط بايثون مع أمثلة

تم النشر بتاريخ 2024-11-08
تصفح:990

A Quick Guide to the Python threading Module with Examples

مقدمة

توفر وحدة الترابط في Python واجهة عالية المستوى لإنشاء وإدارة سلاسل الرسائل، مما يتيح لك تشغيل التعليمات البرمجية بشكل متزامن. يمكن أن يكون هذا مفيدًا بشكل خاص للمهام التي يمكن تنفيذها بالتوازي، مثل العمليات المرتبطة بالإدخال/الإخراج. فيما يلي قائمة بالأساليب والوظائف شائعة الاستخدام في وحدة الترابط، مع أمثلة موجزة.

1. الموضوع ()

فئة الخيط هي قلب وحدة الترابط. يمكنك إنشاء وبدء مواضيع جديدة باستخدام هذا الفصل.

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.current_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. تعداد ()

إرجاع قائمة بجميع كائنات الموضوع النشطة حاليًا.

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

print(threading.enumerate())  # Lists all active threads

7. active_count()

يرجع عدد كائنات الموضوع النشطة حاليًا.

print(threading.active_count())  # Returns the number of active threads

8. قفل ()

كائن القفل هو قفل بدائي يستخدم لمنع حالات السباق. يمكنك استخدامه لضمان وصول مؤشر ترابط واحد فقط إلى مورد مشترك في المرة الواحدة.

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. رلوك ()

يسمح قفل إعادة الدخول للخيط بالحصول على القفل عدة مرات دون حظر نفسه.

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 = 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 = 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 بتحديد عدد سلاسل الرسائل التي يمكنها الوصول إلى المورد في وقت واحد.

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(True) أو تمرير daemon=True إلى مُنشئ الخيط.

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

خاتمة

تعد وحدة الترابط أداة قوية للتعامل مع التزامن في Python. يوفر فئات وطرق متعددة لإنشاء سلاسل الرسائل والتحكم فيها، مما يجعل من السهل تنفيذ التعليمات البرمجية بالتوازي. من استخدام كائنات Thread الأساسية إلى إدارة المزامنة مع Lock وSemaphore، تعد هذه الوحدة ضرورية لكتابة برامج Python المتزامنة.

بيان الافراج تم إعادة إنتاج هذه المقالة على: https://dev.to/usooldatascience/a-quick-guide-to-the-python-threading-module-with-examples-2b3g?1 إذا كان هناك أي انتهاك، يرجى الاتصال بـ Study_golang@163 .com لحذفه
أحدث البرنامج التعليمي أكثر>

تنصل: جميع الموارد المقدمة هي جزئيًا من الإنترنت. إذا كان هناك أي انتهاك لحقوق الطبع والنشر الخاصة بك أو الحقوق والمصالح الأخرى، فيرجى توضيح الأسباب التفصيلية وتقديم دليل على حقوق الطبع والنشر أو الحقوق والمصالح ثم إرسالها إلى البريد الإلكتروني: [email protected]. سوف نتعامل مع الأمر لك في أقرب وقت ممكن.

Copyright© 2022 湘ICP备2022001581号-3