ABOUT ME

-

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

    // Example06_SpinLock2.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다.
    //
    #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;
    long g_key =1;

    int _tmain(int argc, _TCHAR* argv[])
    {
     

     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]);
     }

     return 0;
    }

    unsigned int WINAPI writeCharacter(LPVOID param)
    {
     char ch = *((char *)param);
     
     LONG key = g_key;
     while(1 != ::InterlockedCompareExchange(&g_key, 0 ,1));  //( 조건 ? 참 : 거짓)과 같다
     /***************임계영역 *************************/
     for(int i = 0; i< 1000; ++i)
     {
      g_string += ch;
     }
     /**************************************************/
     g_key = 1; 
     
     return 0;
    }

     

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

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