簡體   English   中英

Python 來自不同文件的線程函數

[英]Python Threading functions from different files

我創建了一個 python 文件,該文件創建了一個從兩個不同文件調用函數的線程

import objDetection_heartbeat
import combindedsensors
from threading import Thread

threads = []

sensors_thread = Thread(name="Sensors", target=combinedsensors.ping)
threads.append(sensors_thread)
sensors_thread.start()

heartbeat_thread = Thread(name="Heartbeat", 
target=objDetection_heartbeat.heartbeat_send)
threads.append(heartbeat_thread)
heartbeat_thread.start()

heartbeat_send function 每 5 秒發送一條消息。 combinesensors.ping 計算兩個對象之間的距離。

我創建的python線程文件只調用了心跳function。 我每 5 秒看到一次,但我不知道為什么它不調用 sensor_thread。 看來我可以運行其中一個,但不能同時運行。 我創建線程的原因是因為心跳是間隔的,而不是等待 5 秒,我試圖與心跳並行調用傳感器 function。

Python 線程是綠色線程,這意味着它們“模擬”真實線程。 實際上,您有一個可用的線程,可以無縫地從一段代碼跳轉到另一段代碼。 CPU 綁定代碼不會受益於 Python 線程功能。

我發現這個問題提供了詳細的解釋: Green-threads and thread in Python

以下可能是更好的解決方案:

yield from asyncio.sleep(1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM