同じスレッドでEnterCriticalSectionを2回呼び出すテストについて

4634 ワード

#include "stdafx.h"
#include <iostream>
using namespace std;
#include <windows.h>
#include <process.h>
CRITICAL_SECTION cs;

//1. EnterCriticalSection 
// : 
/*
int _tmain(int argc, _TCHAR* argv[])
{
    InitializeCriticalSection(&cs);
    EnterCriticalSection(&cs);
    EnterCriticalSection(&cs);
    for(int i = 0;i < 20;i++)
    {
        cout<<"MainThread:"<<i<<endl;
        Sleep(1000);
    }
    LeaveCriticalSection(&cs);
    DeleteCriticalSection(&cs);
    system("pause");
    return 0;
}
*/


//2. EnterCriticalSection, LeaveCriticalSection  EnterCriticalSection
// :   EnterCriticalSection   LeaveCriticalSection 
unsigned  __stdcall ThreadPorc ( void * )
{
    for(int i = 0;i<20;i++)
    {
        EnterCriticalSection(&cs);
        cout<<" 2 "<<endl;
        break;
        LeaveCriticalSection(&cs);
        Sleep(1000);
    }
    return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
    InitializeCriticalSection(&cs);
    EnterCriticalSection(&cs);
    EnterCriticalSection(&cs);
    _beginthreadex(NULL,0,ThreadPorc,NULL,0,NULL);
    for(int i = 0;i < 20;i++)
    {
        if(i == 10)
        {
            LeaveCriticalSection(&cs);
        }
        cout<<"MainThread:"<<i<<endl;
        Sleep(1000);
    }
    LeaveCriticalSection(&cs);
    Sleep(5000);
    DeleteCriticalSection(&cs);
    system("pause");
    return 0;
}