Windows tls 测试
来源:互联网 发布:关于知行的诗句 编辑:程序博客网 时间:2024/06/08 07:12
一、概念
tls:Thread Local Storage,是Windows为解决一个进程中多个线程同时访问全局变量而提供的机制。
二、简单使用
1.测试代码
#include "stdio.h"#include <WTypes.h>static DWORD tls_index = 0;static bool is_show_thread_begin = false;static bool is_finish_work = false;#define print_tls(module,index,value) \ printf("%s module , index %u, value %d\n", module, index, value)DWORD WINAPI my_thread_work(LPVOID){ while(!is_show_thread_begin) Sleep(100); TlsSetValue(tls_index, (LPVOID)0); int value = 0; while((value = (int)TlsGetValue(tls_index)) < 3) { Sleep(1000); value++; TlsSetValue(tls_index, (LPVOID)value); print_tls("===my_thread_work", tls_index, (int)TlsGetValue(tls_index)); } is_finish_work = true;; return 0;}DWORD WINAPI my_thread_show(LPVOID){ is_show_thread_begin = true; while(!is_finish_work) { print_tls("my_thread_show", tls_index, (int)TlsGetValue(tls_index)); Sleep(1000); } return 0;}int main(int argc, char **argv){ tls_index = TlsAlloc(); // 申请线程局部变量 if (TLS_OUT_OF_INDEXES != tls_index) { TlsSetValue(tls_index, (LPVOID)1000); print_tls("main", tls_index, (int)TlsGetValue(tls_index)); HANDLE hWork = CreateThread(NULL, 0, my_thread_work, (LPVOID)0, 0, NULL); HANDLE hShow = CreateThread(NULL, 0, my_thread_show, (LPVOID)1, 0, NULL); WaitForSingleObject(hWork, INFINITE); WaitForSingleObject(hShow, INFINITE); print_tls("main", tls_index, (int)TlsGetValue(tls_index)); TlsFree(tls_index); // 释放线程局部变量 } else { printf("out of tls indexs"); } return 0;}
2.运行结果