ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • CriticalSection
    Operations Dev/writech 2010. 12. 10. 18:22

    // Example04_CriticalSection.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다.
    // CriticalSection은 유저모드(재귀 스핀락)인데 오늘은 일반 락

    #include "stdafx.h"

    #include<windows.h>
    #include<process.h>

    #include<string>
    #include<iostream>
    using namespace std;

    unsigned int WINAPI writeCharacter(LPVOID param);

    string g_string;
    int const MAX_THREAD = 5;
    CRITICAL_SECTION  g_criticalSection;

    int _tmain(int argc, _TCHAR* argv[])
    {
     ::InitializeCriticalSection(&g_criticalSection);

     DWORD threadIDs[MAX_THREAD];
     HANDLE threadHandles[MAX_THREAD];
     char alphas[MAX_THREAD];

     for(int i =0; i<MAX_THREAD; ++i)
     {
      alphas[i] = 'a' + i;

      threadHandles[i] = (HANDLE) ::_beginthreadex( NULL, 0 , writeCharacter,(LPVOID*)(&alphas[i]),0,(unsigned int *)&threadIDs[i]);
     }
     
     DWORD result = ::WaitForMultipleObjects(MAX_THREAD, &threadHandles[0],TRUE,INFINITE);
     if(result == WAIT_OBJECT_0)
     {
      
      cout<<g_string;
      
     }
     for(int i = 0; i< MAX_THREAD; ++i)
     {
      CloseHandle(threadHandles[i]);
     }
     ::DeleteCriticalSection(&g_criticalSection);

     return 0;
    }

    unsigned int WINAPI writeCharacter(LPVOID param)
    {
     char ch = *((char *)param);
     ::EnterCriticalSection(&g_criticalSection);
     /***************임계영역 *************************/
     for(int i = 0; i< 1000; ++i)
     {
      g_string += ch;
     }
     /**************************************************/
     ::LeaveCriticalSection(&g_criticalSection);
     
     return 0;
    }

    'Operations Dev > writech' 카테고리의 다른 글

    Mutex  (0) 2010.12.10
    Semaphore  (0) 2010.12.10
    SpinLock  (0) 2010.12.10
    SpinLock2  (0) 2010.12.10
    SimpleConcurrency  (0) 2010.12.10
Designed by Tistory.