0

I created a python file that creates a thread calling functions from two different files

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 is sending out a message every 5 seconds. combinedsensors.ping calculates the distance between two objects.

The python thread file I created only calls the heartbeat function. I see that coming through every 5 seconds, but I dont know why it isn't calling sensor_thread. It seems I can run one or the other, but not both. The reason I'm creating a thread is because the heartbeat is on an interval and instead of having to wait 5 seconds, I was attempting to call the sensor function in parallel with the heartbeat.

Van Hour
  • 3
  • 3
  • Have you tried replacing the functions with two simple dummy function for your threads? Does it work that way? – thuyein Jun 25 '20 at 00:17
  • I created 2 dummy functions with different sleep timer and I got that to work. I ended up moving the heartbeat function into the sensor file, rather than having it as it’s own file. I applied the same logic to my heartbeat and sensors and everything is working as a expected. – Van Hour Jun 25 '20 at 01:21
  • It should work no matter where you put the functions. What else did you change? – thuyein Jun 25 '20 at 01:28

1 Answers1

-1

Python threads are green threads, meaning that they "simulate" real thread. In fact you have a single thread available that seemlessly jumps from a piece of code to another. CPU bound code will not benefit from Python threads capability.

I found this question that provides detailed explanations: Green-threads and thread in Python

The following might be a better solution:

yield from asyncio.sleep(1)
Tarik
  • 10,810
  • 2
  • 26
  • 40
  • What you said about the code that blocks (`sleep`) is wrong. https://pastebin.com/cGauZGLP here is a simple thread example I created. If what you said is true, the second print statement from `anotherfunc` would never be printed. Sleep only does blocking per thread basis. Python switch context on threads periodically. [thread proc imge](https://callhub.io/wp-content/uploads/2016/06/python-gil-visualization.png) – thuyein Jun 25 '20 at 00:15
  • @Thu Yein Tun Thanks for your correction. I have removed my statement about blocking. – Tarik Jun 25 '20 at 14:58