(26)接上一篇的函数 WaitOnAddress ( ) 使线程睡眠,本函数 WakeByAddressSingle () 则是唤醒睡眠的进程,这俩函数用于 windows 平台上的多线程:
++ 举例代码:
#include <windows.h>
#include <iostream>
// 全局变量,可供所有线程访问
ULONG g_SharedValue = 0;
ULONG g_CompareValue = 0;
DWORD WINAPI WaitThread(LPVOID lpParam) // 本函数在线程中执行
{
while (true) { // 等待 g_SharedValue 的值变为非0
if (WaitOnAddress(&g_SharedValue, &g_CompareValue, sizeof(ULONG), INFINITE)) {
std::cout << "WaitThread: g_SharedValue changed to " << g_SharedValue << std::endl;
break; // 假设只等待一次
}
}
return 0;
}
int main() {
HANDLE hWaitThread = CreateThread(NULL, 0, WaitThread, NULL, 0, NULL); // 创建等待线程
if (!hWaitThread) { // 创建线程失败
std::cerr << "CreateThread failed, error: " << GetLastError() << std::endl;
return 1;
}
Sleep(1000); // 等待1秒 ,模拟一些工作,然后更改g_SharedValue的值
g_SharedValue = 1; // 更改全局变量的值
WakeByAddressSingle(&g_SharedValue); // 唤醒等待线程
WaitForSingleObject(hWaitThread, INFINITE); // 等待等待线程结束
CloseHandle(hWaitThread); // 关闭线程句柄
return 0;
}
(27) 与上面的函数类似的函数 WakeByAddressAll ( ):
++ 举例:
#include <windows.h>
#include <iostream>
// 全局变量,可供所有线程访问
ULONG g_SharedValue = 0;
ULONG g_CompareValue = 0;
DWORD WINAPI WaitThread(LPVOID lpParam) {
while (true) {
// 等待g_SharedValue的值变为非0
if (WaitOnAddress(&g_SharedValue, &g_CompareValue, sizeof(ULONG), INFINITE)) {
std::cout << "WaitThread: g_SharedValue changed to " << g_SharedValue << std::endl;
break; // 假设只等待一次
}
}
return 0;
}
int main() {
// 创建多个等待线程
HANDLE hWaitThreads[10];
for (int i = 0; i < 10; ++i) {
hWaitThreads[i] = CreateThread(NULL, 0, WaitThread, NULL, 0, NULL);
if (!hWaitThreads[i]) {
std::cerr << "CreateThread failed, error: " << GetLastError() << std::endl;
return 1;
}
}
// 模拟一些工作,然后更改g_SharedValue的值
Sleep(1000); // 等待1秒
g_SharedValue = 1; // 更改全局变量的值
// 唤醒所有等待线程
WakeByAddressAll(&g_SharedValue); // <---------------------------------
// 等待所有等待线程结束
for (int i = 0; i < 10; ++i) {
WaitForSingleObject(hWaitThreads[i], INFINITE);
CloseHandle(hWaitThreads[i]);
}
return 0;
}
(28)wins 平台函 _InterlockedExchange ( ), 这是 windows 平台很基础的多线程领域的函数,被应用到 STL 模板库的编写里:
(29)
谢谢