windows编程: TLS机制

107 阅读1分钟

线程局部存储(Thread Local Storage,TLS)

线程局部存储(TLS)是一种机制,允许每个线程拥有自己的数据副本。这在多线程编程中非常有用,特别是当不同线程需要独立的变量副本时。 在 Windows 中,可以使用 TlsAlloc、TlsGetValueTlsSetValue 等 API 来实现 TLS。

代码示例:

#include <windows.h>
#include <iostream>

DWORD tlsIndex; // TLS 索引

DWORD WINAPI ThreadFunc(LPVOID lpParam) {
    // 为当前线程设置 TLS 数据
    int* threadData = new int; // 动态分配内存
    *threadData = GetCurrentThreadId(); // 存储线程 ID

    // 设置 TLS 数据
    TlsSetValue(tlsIndex, threadData);

    // 获取并输出 TLS 数据
    int* storedData = (int*)TlsGetValue(tlsIndex);
    std::cout << "Thread " << GetCurrentThreadId() << " has data: " << *storedData << std::endl;

    // 清理
    delete threadData; // 释放动态分配的内存
    return 0;
}

int main() {
    // 分配 TLS 索引
    tlsIndex = TlsAlloc();
    if (tlsIndex == TLS_OUT_OF_INDEXES) {
        std::cerr << "TlsAlloc failed!" << std::endl;
        return 1;
    }

    // 创建多个线程
    HANDLE threads[3];
    for (int i = 0; i < 3; ++i) {
        threads[i] = CreateThread(NULL, 0, ThreadFunc, NULL, 0, NULL);
    }

    // 等待所有线程结束
    WaitForMultipleObjects(3, threads, TRUE, INFINITE);

    // 关闭线程句柄
    for (int i = 0; i < 3; ++i) {
        CloseHandle(threads[i]);
    }

    // 释放 TLS 索引
    TlsFree(tlsIndex);
    return 0;
}

其他

C++ TLS: 是 C++ 标准的一部分,从 C++11 开始引入,使用 thread_local 关键字实现线程局部存储。

thread_local int myVar = 0; // 每个线程都有自己的 myVar 实例