windows_37_windows_Sync
// windows_37_windows_Sync.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <windows.h>
CHAR *g_pszText = NULL;
DWORD g_nTlsIndex = NULL; //全局索引号
void print( )
{
printf( "%s\n", g_pszText );
//从索引中把值取出来
CHAR *pszText = (CHAR*)TlsGetValue( g_nTlsIndex );
printf( "TLS: %s\n", pszText );
}
DWORD WINAPI PrintProc( LPVOID pParam )
{
CHAR *pszText = (CHAR*)pParam;
g_pszText = (CHAR *)malloc( 100 );
strcpy_s( g_pszText, strlen( pszText )+1, pszText );
//将值保存到TLS索引当中
TlsSetValue( g_nTlsIndex, g_pszText );
while (true)
{
print( );
Sleep( 1000 );
}
return 0;
}
//
void Create( )
{
HANDLE hThread = NULL;
DWORD nThreadID = 0;
CHAR szText1[] = "ThreadProc-------";
hThread = CreateThread( NULL, 0, PrintProc, szText1, 0, &nThreadID );
//线程第二
CHAR szText2[] = "ThreadProc2***********";
hThread = CreateThread( NULL, 0, PrintProc, szText2, 0, &nThreadID );
getchar( );
WaitForSingleObject( hThread, INFINITE );
CloseHandle( hThread );
}
int _tmain(int argc, _TCHAR* argv[])
{
//1、创建 TLS 索引
//TlsAlloc
g_nTlsIndex = TlsAlloc( );
//创建线程
Create( );
//释放索引
TlsFree( g_nTlsIndex );
return 0;
}
时间: 2024-10-07 05:22:58