使用_beginthreadex 来创建线程比CreateThread 更加的安全,但是_beginthreadex 需要传入的参数和CreateThread并不是一样的,但基本相同,只需要做一些转换,线程的同步采用两种方式实现,一是采用关键代码段(已注释)和事件内核对象来实现。 以下是实现:
#include "stdafx.h"
#include "windows.h"
#include <PROCESS.H>
#include <stddef.h>
#include <iostream.h>
int g_nCount = 0;
typedef unsigned (__stdcall *PTHREAD_START) (void*);
//CRITICAL_SECTION gcs;
HANDLE hEvent = NULL;
DWORD WINAPI ThreadProc1(PVOID *pData)
{
while (g_nCount < 100)
{
// EnterCriticalSection(&gcs);
WaitForSingleObject(hEvent,50000);
g_nCount++;
cout << "thread1" << endl;
cout << g_nCount << endl;
SetEvent(hEvent);
Sleep(1);
// LeaveCriticalSection(&gcs);
}
return 0;
}
DWORD WINAPI ThreadProc2(PVOID *pData)
{
while (g_nCount < 100)
{
// EnterCriticalSection(&gcs);
WaitForSingleObject(hEvent,50000);
g_nCount++;
cout << "thread2" << endl;
cout << g_nCount << endl;
SetEvent(hEvent);
Sleep(1);
// LeaveCriticalSection(&gcs);
}
return 0;
}
int main(int argc, char* argv[])
{
// InitializeCriticalSection(&gcs);
hEvent = CreateEvent(NULL,FALSE,TRUE,NULL);
HANDLE handl1 = (HANDLE)_beginthreadex(NULL,0,(PTHREAD_START)(ThreadProc1),NULL,0,NULL);
CloseHandle(handl1);
HANDLE handl2 = (HANDLE)_beginthreadex(NULL,0,(PTHREAD_START)(ThreadProc2),NULL,0,NULL);
CloseHandle(handl2);
int m = 0;
cin >> m;
// DeleteCriticalSection(&gcs);
return 0;
}
1123




被折叠的 条评论
为什么被折叠?



