Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

notify thread about changes in variable (signals?)

I have main() and thread in the same program.

there is a variable named "status", that can get several values

I need that when the variable changes, to notify the thread (the thread cnat wait for the status variable, it is already doing fluent task) .

is there an easy way to do so? similar to interrupts? how about signals?

the function inside the main:

int main()
{

 char *status;
 ... 
 ...
 while (1)
 {
 switch (status)
   {
     case: status1 ...notify the thread
     case: status2 ...notify the thread
     case: status3 ...notify the thread
   }
 }

}

if someone could give me an example it will be great! thanks!

like image 666
user1673206 Avatar asked Nov 25 '25 14:11

user1673206


2 Answers

Since you're already using the pthread library you can use conditional variables to tell the thread that there is data ready for processing. Take a look at this StackOverflow question for more information.

like image 150
Sean Avatar answered Nov 28 '25 03:11

Sean


I understand that you do not want to wait indefinitely for this notification, however C++ only implements cooperative scheduling. You cannot just pause a thread, fiddle with its memory, and resume it.

Therefore, the first thing you have to understand is that the thread which has to process the signal/action you want to send must be willing to do so; which in other words means must explicitly check for the signal at some point.

There are multiple ways for a thread to check for a signal:

  • condition variable: they require waiting for the signal (which might be undesirable) but that wait can be bounded by a duration
  • action queue (aka channel): you create a queue of signals/actions and every so often the target thread checks for something to do; if there is nothing it just goes on doing whatever it has to do, if there is something you have to decide whether it should do everything or only process the N firsts. Beware of overflowing the queue.
  • just check the status variable directly every so often, it does not tell you how many times it changed (unless it keeps an history: but then we are back to the queue), but it allows you to amend your ways.

Given your requirements, I would think that the queue is probably the best idea among those three.

like image 21
Matthieu M. Avatar answered Nov 28 '25 02:11

Matthieu M.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!