Waiting for a variable

I am working on a program that should be able to monitor another process. I do not have the code of this other process and thus cannot modify the code. This process changes a variable after it is done with a specific task. I need to detect this change so my own program can execute a function after this task is done.

I have already managed to get the actual variable, so it could be treated as if it were located in my own program. So this case could be simplified to:

1
2
3
4
5
6
7
8
9
10
11
12
volatile bool task_finished = false;

void task_finished();

int main()
{
   //Wait for the variable to change
   ...
   //Now execute a function
   task_finished();
   return 0;
}


Now I know it would be possible to use a loop to busy-wait for the variable to change, like this:

1
2
while(!task_finished)
    ;


But this would waste a lot of CPU time, so I'm looking for a less CPU-intensive solution. Is is possible under Windows to wait for this variable to change without having to modify the external process in any way?
If you don't mind not acting on the changed variable instantly, you could add a sleep in the while loop.
Acting on the changed variable instantly is quite important actually, sorry for not adding that to the original post. So sleeping in the loop won't solve the problem.
Instant is physically impossible. How much time is permitted?
Since the variable can change at most once in the 500ms, a little less than that seems to be the longest possible time that waiting is permitted.
A spinlock seems like a sensible solution to me in this situation, if responding quickly is important.
Then it looks like that will be the final solution. Thank you all for all your help.
Topic archived. No new replies allowed.