Thread to wait infinitely in a loop until a flag state change, then call function.
pseudo code illustration:
while (true)
{
while (!flag)
{
sleep(1);
}
clean_upfunction();
}
Currently :
No:
Question:
For Windows (which you have this tagged for), you want to look at WaitForSingleObject . Use a Windows Event (with CreateEvent), then wait on it; the other thread should call SetEvent. All native Windows, no MFC or anything else required.
If you're not on Windows, and are instead on a POSIXish box, pthread_cond_wait
is the best match:
/* signaler */
pthread_mutex_lock(mutex);
flag = true;
pthread_cond_signal(cond);
pthread_mutex_unlock(mutex);
/* waiter */
pthread_mutex_lock(mutex);
do {
pthread_cond_wait(cond, mutex);
} while (!flag);
pthread_mutex_unlock(mutex);
The classic self-pipe trick is easier and cooler though :) Works on systems without pthreads
too.
/* setup */
int pipefd[2];
if (pipe(pipefd) < 0) {
perror("pipe failed");
exit(-1);
}
/* signaler */
char byte = 0;
write(pipefd[0], &byte, 1); // omitting error handling for brevity
/* waiter */
char byte;
read(pipefd[1], &byte, 1); // omitting error handling for brevity
The waiter will block on the read
(you don't set O_NONBLOCK
) until interrupted (which is why you should have error handling) or the signaler writes a byte.
Take a look at condition_variable in Boost.Thread.
It is portable, easier to use than the platform-specific options. Moreover, IIUC, the upcoming C++0x std::condition_variable was modeled after it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.