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

การตั้งกระทู้ใหม่ใน Python


หากต้องการวางไข่เธรดอื่น คุณต้องเรียกใช้เมธอดต่อไปนี้ในโมดูลเธรด -

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

การเรียกเมธอดนี้ช่วยให้สร้างเธรดใหม่ได้อย่างรวดเร็วและมีประสิทธิภาพทั้งใน Linux และ Windows

การเรียกเมธอดจะส่งคืนทันทีและเธรดย่อยเริ่มต้นและเรียกใช้ฟังก์ชันด้วยรายการ args ที่ส่งผ่าน เมื่อฟังก์ชันส่งคืน เธรดจะสิ้นสุดลง

ที่นี่ args เป็นอาร์กิวเมนต์ทูเพิล ใช้ทูเพิลว่างเพื่อเรียกใช้ฟังก์ชันโดยไม่ผ่านอาร์กิวเมนต์ใดๆ kwargs เป็นพจนานุกรมทางเลือกของอาร์กิวเมนต์คำหลัก

ตัวอย่าง

#!/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

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