线程同步之 CRITICAL_SECTION
//线程同步之 CRITICAL_SECTION
#include
#include
using namespace std;
CRITICAL_SECTION cs;
DWORD WINAPI f_hello(LPVOID );
DWORD WINAPI f_hi(LPVOID );
int main(int argc, char *argv[])
{
HANDLE h_hello,h_hi;
InitializeCriticalSection(&cs);
h_hello=CreateThread(NULL,0,f_hello,NULL,0,NULL);//hello
h_hi=CreateThread(NULL,0,f_hi,NULL,0,NULL);//hi
CloseHandle(h_hello);
CloseHandle(h_hi);
getchar();
DeleteCriticalSection(&cs);//此句放在getchar()前很容易崩溃,不难理解
return 0;
}
DWORD WINAPI f_hello(LPVOID lpParamter){
EnterCriticalSection(&cs);
cout<<"hello\n";
// LeaveCriticalSection(&cs);
ExitThread(0);
}
DWORD WINAPI f_hi(LPVOID lpParamter){
EnterCriticalSection(&cs);
cout<<"hi\n";
//LeaveCriticalSection(&cs);
ExitThread(0);
}
/*只会输出hi或者 hello 因为 临界区保证同一时刻只能有一个线程访问临界区代码 。
注意:输出hi 或是 hello 每次结果不一定哦!
LeaveCriticalSection(&cs);若两个此语句不注释,则hi 与 hello 都能输出。
*/