64,646
社区成员
发帖
与我相关
我的任务
分享
#include <windows.h>
#include <process.h>
#include <iostream>
using namespace std;
long g_iData = 0; // 全局变量
// 线程体
unsigned int __stdcall ThreadFunc(void* param)
{
g_iData++;
//InterlockedExchangeAdd(&g_iData,155);
return 0;
}
unsigned int __stdcall ThreadFunc2(void* param)
{
g_iData=g_iData+3;
//InterlockedExchange(&g_iData, 4);
return 0;
}
void main()
{
unsigned int tid1 = 0;
unsigned int tid2 = 0;
HANDLE tHandle = NULL;
HANDLE tHandle2 = NULL;
tHandle= (HANDLE)_beginthreadex(NULL, 0,
ThreadFunc, 0, 0, &tid1);
ResetEvent(tHandle);
WaitForSingleObject(tHandle, INFINITE);//不等待线程1结束的话,可能会有下面的输出语句先执行而输出1
cout<<g_iData<<endl;
cout<<g_iData<<endl;
tHandle2 = (HANDLE)_beginthreadex(NULL, 0,
ThreadFunc2, 0, 0, &tid2);
cout<<g_iData<<endl;
system("pause");
}
#include <windows.h>
#include <process.h>
#include <iostream>
using namespace std;
long g_iData = 0; // 全局变量
// 线程体
unsigned int __stdcall ThreadFunc(void* param)
{
//Sleep(100);
g_iData++;
//InterlockedExchangeAdd(&g_iData,155);
return 0;
}
unsigned int __stdcall ThreadFunc2(void* param)
{
g_iData=g_iData+3;
//InterlockedExchange(&g_iData, 4);
return 0;
}
void main()
{
unsigned int tid1 = 0;
unsigned int tid2 = 0;
HANDLE tHandle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
HANDLE tHandle2 = ::CreateEvent(NULL, FALSE, FALSE, NULL);
tHandle= (HANDLE)_beginthreadex(NULL, 0,
ThreadFunc, 0, 0, &tid1);
ResetEvent(tHandle);
WaitForSingleObject(tHandle, INFINITE);
int a=GetLastError();
cout<<g_iData<<endl;
cout<<g_iData<<endl;
tHandle2 = (HANDLE)_beginthreadex(NULL, 0,
ThreadFunc2, 0, 0, &tid2);
cout<<g_iData<<endl;
system("pause");
}