<atomic> 注释9:win 平台函数 WakeByAddressSingle () 与 WakeByAddressAll (),wins 平台函 _InterlockedExchange ( )

(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)

谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值