Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีนำ Concurrency มาใช้กับ Threads ใน Python

บทนำ

Python มีหลายวิธีสำหรับ concurrent programming: threads, subprocesses, generators ฯลฯ ก่อนอื่นต้องเข้าใจ Concurrency คืออะไร

Concurrency คือตรรกะภายในโปรแกรมเดียวที่เปิด path การ execute หลายเส้นทางพร้อมกัน เช่น separate I/O streams, SQL queries ทำให้ดูเหมือน simultaneous และ independent

ขั้นตอนการทำงาน

1. โค้ดแบบ Sequential (Single Thread)


import requests
tutorialpoints_url = [
    'https://www.tutorialspoint.com/python/index.htm',
    'https://www.tutorialspoint.com/cplusplus/index.htm',
    'https://www.tutorialspoint.com/java/index.htm',
    'https://www.tutorialspoint.com/html/index.htm',
    'https://www.tutorialspoint.com/cprogramming/index.htm'
]

def visit_site(site_url):
    response = requests.get(site_url)
    print(f' *** {site_url} returned {response.status_code} after {response.elapsed} seconds')

if __name__ == '__main__':
    for site_url in tutorialpoints_url:
        visit_site(site_url)
    print(" *** end of the program ***")

ผล: รอแต่ละ URL ตามลำดับ รวมเวลาทั้งหมด = ผลรวมเวลาแต่ละ request

2. โค้ดแบบ Threaded (Concurrent)


from threading import Thread

def visit_site(site_url):
    response = requests.get(site_url)
    print(f' *** {site_url} returned {response.status_code} after {response.elapsed} seconds')

if __name__ == '__main__':
    for site_url in tutorialpoints_url:
        t = Thread(target=visit_site, args=(site_url,))
        t.start()

ผล: ส่ง request ทั้ง 5 พร้อมกัน เวลารวม ≈ เวลาของ request ที่ช้าที่สุด

การตรวจสอบสถานะ Thread


if t.is_alive():
    print(f' *** {t} is Still executing')
else:
    print(f' *** {t} is Completed')

จุดสำคัญ

  • threading.Thread ใช้ execute Python callable ใน thread แยก
  • start() เริ่ม thread (invoke target function)
  • Threads จัดการโดย OS แบบ preemptive multitasking
  • เหมาะสำหรับ I/O-bound tasks (network requests, file I/O, database queries)
  • ไม่เหมาะ สำหรับ CPU-bound tasks เพราะ GIL (Global Interpreter Lock)

ข้อควรระวัง

  • Shared state ต้องใช้ Lock/Queue ป้องกัน race condition
  • Exception ใน thread ไม่ propagate ไป main thread อัตโนมัติ
  • จำนวน thread มากเกินไป → overhead สูง ควรใช้ ThreadPoolExecutor