让你的后台线程在你的主线程上为一个互斥变量设置一个标志,告诉它(主线程)可以安全地继续做它正在做的事情。它有点像一个停车灯——所有角落(两侧)都有相互关联的灯。
您的主线程不会暂停,但您可以有一个 while 循环来处理(gui 和其他)消息,但在设置互斥变量 get 之前它不会中断循环——这将发生在后台线程上。
以下是一些帮助您入门的参考资料:
编辑——根据请求:
在全局范围内,定义您的互斥量句柄和变量:
HANDLE sharedMemoryMutex = CreateMutex(NULL, FALSE, "My mutex =)!");
BOOL good2Go = false;
然后,在您的后台线程中,它将如下所示:
void wait() {
// First, we sleep...
sleep(3000);
// Now, we request a lock on the good2Go variable, so that when we write to
// it, no other thread is:
DWORD dwWaitResult = WaitForSingleObject(sharedMemoryMutex, INFINITE);
if (dwWaitResult == WAIT_OBJECT_0 || dwWaitResult == WAIT_ABANDONED) {
if (dwWaitResult == WAIT_ABANDONED) {
// Shared memory is maybe in inconsistent state because other program
// crashed while holding the mutex. Check the memory for consistency
...
}
// Access your shared memory
good2Go = true;
// Release the lock so that the main thread can read the variable again..
ReleaseMutex(sharedMemoryMutex);
}
然后在你的主线程中,它看起来像这样:
// Create your background wait thread:
// .....
while(true) {
// Handle messages so that your program doesn't appear frozen.
// You will have to do your research on this one =)
YourMessageHandler();
// Request a lock on the good2Go variable, so we can read it w/o corrupting it
DWORD dwWaitResult = WaitForSingleObject(sharedMemoryMutex, INFINITE);
if (dwWaitResult == WAIT_OBJECT_0 || dwWaitResult == WAIT_ABANDONED) {
if (dwWaitResult == WAIT_ABANDONED) {
// Shared memory is maybe in inconsistent state because other program
// crashed while holding the mutex. Check the memory for consistency
...
}
// Exit the loop
if( good2Go ) { ReleaseMutex(sharedMemoryMutex); break; }
ReleaseMutex(sharedMemoryMutex);
}
// Continue your code after the 3 pause....
如果您还不知道,您将不得不弄清楚如何处理消息。此外,您的互斥锁实现可能会有所不同,但是您说您使用的是 VC,所以上面的 win32 实现应该没问题。而且我认为您了解一般概念