ivanseidel / ArduinoThread

⏳ A simple way to run Threads on Arduino
MIT License
955 stars 196 forks source link

Using memory address as ThreadID sometimes gives different threads the same address #42

Open alriedel opened 5 years ago

alriedel commented 5 years ago

In my program, I've created 3 threads and then added them all to a controller thread. However, one thread was never executed (I had print-statements that should have run) and after some debugging I noticed that the size of the controller thread showed 2, when it should have been 3. I did not use thread names. I am only using lambda functions as callback functions for the threads.

Looking at the thread-controllers add function, I saw that a thread is not added when the controller already has a thread with the same ID. I printed the thread-ids of all my threads and it turned out that the 1st and the 3rd thread got the same ID, so the 3rd thread was never added. But this should not be possible as different threads should get different ids?

When I added Serial.println() before and Serial.println(controller.size()) after adding the 3rd thread to the controller, all 3 threads got different IDs. I can not explain this behaviour.

Thus, my conclusion is that using memory address as ThreadID feels unpredictable. Maybe thread id could be substituted by a random number instead? (I did this as a workaround).

EmDash00 commented 5 years ago

Wouldn't using a random number break the idea of using ThreadID to tell if two threads are the same? A random number is not unique to a thread object nor unique in general. By sheer chance, albeit unlikey two threads may get the same random number. Memory addresses are unique per unique thread object.

I'm pretty sure it should be physically impossible for your threads to have the same memory address unless they are actually the same object. That is just how C and C++ works. It's likely that you did something weird while instantiating your objects. Can you show us the code that produces this issue?

Also, if you did do something weird with instantiation and they are the same object, the ThreadController is designed to not contain duplicates of threads.