ด้าย#
การแนะนำ#
เธรดช่วยให้หุ่นยนต์สามารถทำงานหลายอย่างพร้อมกันภายในโปรแกรมเดียวกันได้ ช่วยให้หุ่นยนต์สามารถทำงานหลายอย่างพร้อมกันได้ โดยสามารถดำเนินการต่างๆ ที่เป็นอิสระต่อกันได้ในเวลาเดียวกัน
หมายเหตุ: คุณต้อง กำหนดฟังก์ชันก่อน เพื่อใช้กับเธรด
ตัวสร้าง – สร้างและเริ่มต้นเธรดใหม่
Thread– เริ่มเธรดใหม่ที่รันฟังก์ชันที่ระบุแบบขนานกับโปรแกรมหลัก
การดำเนินการ – ควบคุมเธรดที่กำลังทำงานอยู่
stop– หยุดเธรดด้วยตนเอง มีประโยชน์สำหรับการหยุดพฤติกรรมพื้นหลัง
ผู้สร้าง#
Thread#
Thread สร้างและเริ่มต้นเธรด เมื่อคุณสร้างเธรด คุณสามารถตั้งชื่อเธรดเพื่อหยุดการทำงานเมื่อไม่ต้องการใช้งานอีกต่อไป
วิธีใช้:
my_thread = Thread(my_function)
พารามิเตอร์ |
คำอธิบาย |
|---|---|
|
(ไม่บังคับ) ชื่อสำหรับกระทู้ใหม่ |
|
The name of a previously defined function. |
หมายเหตุ: ฟังก์ชันจะต้อง ถูกกำหนด ก่อน ที่จะถูกเรียกใช้เสมอ
# Drive forward while blinking lights
def blink_lights():
while True:
robot.led.on(ALL_LEDS, RED)
wait(0.5, SECONDS)
robot.led.on(ALL_LEDS, BLUE)
wait(0.5, SECONDS)
blink_lights_thread = Thread(blink_lights)
robot.move_at(0)
# Run multiple threads simultaneously
# Turn right, blink lights and display heading at once
def blink_lights():
while True:
robot.led.on(ALL_LEDS, RED)
wait(0.5, SECONDS)
robot.led.on(ALL_LEDS, GREEN)
wait(0.5, SECONDS)
def display_heading():
while True:
robot.screen.clear_row()
robot.screen.set_cursor(1, 1)
robot.screen.print(f"Heading: {robot.inertial.get_yaw()}")
wait(50, MSEC)
blink_lights_thread = Thread(blink_lights)
display_heading_thread = Thread(display_heading)
robot.turn(RIGHT)
การกระทำ#
stop#
stop หยุดเธรดด้วยตนเอง ซึ่งมีประโยชน์เมื่อไม่ต้องการงานอีกต่อไป หรือเมื่อโปรแกรมต้องการรีเซ็ตเธรด เมื่อเธรดหยุดแล้ว จะไม่สามารถเริ่มต้นใหม่ได้ หากต้องการเรียกใช้อีกครั้ง คุณต้องสร้างเธรดใหม่โดยใช้ Thread
วิธีใช้:
my_thread.stop()
พารามิเตอร์ |
คำอธิบาย |
|---|---|
|
อ็อบเจ็กต์เธรดที่เริ่มต้นไว้ก่อนหน้านี้ นี่คือชื่อที่กำหนดให้เมื่อสร้างเธรดโดยใช้ |
"""
Run multiple threads simultaneously
Turn right, blink lights and display heading at once
Stop blinking lights after 2 seconds
"""
def blink_lights():
while True:
robot.led.on(ALL_LEDS, RED)
wait(0.5, SECONDS)
robot.led.off(ALL_LEDS)
wait(0.5, SECONDS)
def display_heading():
while True:
robot.screen.clear_row()
robot.screen.set_cursor(1, 1)
robot.screen.print(f"Heading: {robot.inertial.get_yaw()}")
wait(50, MSEC)
blink_lights_thread = Thread(blink_lights)
display_heading_thread = Thread(display_heading)
robot.turn(RIGHT)
wait(2, SECONDS)
blink_lights_thread.stop()