Page 1 of 1

Keep a Function Updating Variables While Rest of Program Move Along?

Posted: Wed Aug 15, 2018 9:29 pm
by ElEscalador
I'm re-writing all of my robot code to start actually using classes and because the current version is a mess of noob mistake and patches. I would like it to be full of slightly more advanced mistakes...

So ideally, my sensor class constructor could keep updating bunches of variables from various sources without me having to call to a device and wait for a response - Then I could just call a getVariable() function and the latest data is sitting there waiting for me. I am a little familiar with fork(), but I'm afraid this won't work because it won't be updating the correct set of variables or returning a pointer to the parent..or is there a way? I considered writing memory addresses to a file and reading the file from my parent program, but that doesn't feel like the right way to go. I must not be googling the correct terms either - got any direction for a fella?

Re: Keep a Function Updating Variables While Rest of Program Move Along?

Posted: Wed Aug 15, 2018 11:19 pm
by Paeryn
Threads are what you want to be looking at, you spawn a new thread to handle the updating whilst the rest of your code carries on. You might need to use mutexes or atomics to make sure the updating thread can't update whilst another thread is in the middle of reading and to prevent reading whilst data is being updated. The threads of a process all share the same memory space though they have their own individual stacks for local variables and function calls.

C++ has std::thread, std::atomic & std::mutex, or you can use the traditional C way of using pthread directly.

Re: Keep a Function Updating Variables While Rest of Program Move Along?

Posted: Thu Aug 16, 2018 1:39 am
by ElEscalador
Awesome, thanks once again! When I get this robot army up and running, I'll make sure they know you're a friendly!