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

Starting a New Thread ใน Python - เริ่มเธรดใหม่

เพื่อสร้างเธรดใหม่ (spawn another thread) ต้องเรียกเมธอดต่อไปนี้ในโมดูล thread:

thread.start_new_thread(function, args[, kwargs])

เมธอดนี้ให้วิธีที่รวดเร็วและมีประสิทธิภาพในการสร้างเธรดใหม่ทั้งใน Linux และ Windows เมธอดจะคืนค่าทันที และ child thread เริ่มทำงานเรียก function พร้อม args ที่ส่งมา เมื่อ function คืนค่า เธรดจะสิ้นสุดการทำงาน

args คือ tuple ของอาร์กิวเมนต์ ใช้ empty tuple เพื่อเรียก function โดยไม่ส่งอาร์กิวเมนต์ kwargs เป็น dictionary ของ keyword arguments (optional)

ตัวอย่างโค้ด

#!/usr/bin/python
import thread
import time

# Define a function for the thread
def print_time(threadName, delay):
    count = 0
    while count < 5:
        time.sleep(delay)
        count += 1
        print "%s: %s" % (threadName, time.ctime(time.time()))

# Create two threads as follows
try:
    thread.start_new_thread(print_time, ("Thread-1", 2,))
    thread.start_new_thread(print_time, ("Thread-2", 4,))
except:
    print "Error: unable to start thread"

while 1:
    pass

ผลลัพธ์ตัวอย่าง

Thread-1: Thu Jan 22 15:42:17 2009
Thread-1: Thu Jan 22 15:42:19 2009
Thread-2: Thu Jan 22 15:42:19 2009
Thread-1: Thu Jan 22 15:42:21 2009
Thread-2: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:25 2009
Thread-2: Thu Jan 22 15:42:27 2009
Thread-2: Thu Jan 22 15:42:31 2009
Thread-2: Thu Jan 22 15:42:35 2009

แม้จะมีประสิทธิภาพสำหรับ low-level threading แต่โมดูล thread จำกัดมากเมื่อเทียบกับโมดูล threading ใหม่กว่า