Critical Section ¶
μλμ° μ μ λ 벨 λκΈ°ν λ°©λ². κ°μ₯ μ¬μ©μ΄ κ°λ¨νλ€.
VS.NET Example ¶
MSDN μμ λλΆλΆ μμ λ₯Ό κ°μ Έλ€κ° μλνκ² λ§λ€μμ΅λλ€. VS.NET μ΄μμμ μλν©λλ€. VS6.0μμ μ±κ³΅νμ λΆ μμΌλ©΄ μλ €μ£ΌμΈμ.
VS.NETμμλ ν¨μμ΄λ¦μ μΈμνμ§ λͺ»νλ κ²½μ° νλ‘μ νΈ μΈν
μμ MFCλΌμ΄λΈλ¬λ¦¬λ₯Ό μ¬μ©νλλ‘ ν΄λ³΄μΈμ.
~cpp // crt_begthrdex.cpp //http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt__beginthread.2c_._beginthreadex.asp // compile with: /MT #include <windows.h> #include <stdio.h> #include <process.h> unsigned Counter; CRITICAL_SECTION cs; //http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/overlapped_str.asp unsigned __stdcall ThreadedFunction( void* pArguments ) { printf( "In second thread...n" ); while ( Counter < 100 ){ EnterCriticalSection(&cs); printf( "Thread ID %d => %dn", pArguments, Counter); Counter++; LeaveCriticalSection(&cs); } _endthreadex( 0 ); return 0; } int main() { HANDLE hThread, hThread2; unsigned threadID = 1; unsigned threadID2 = 2; printf( "Creating second thread...n" ); // Create the second thread. hThread = (HANDLE)_beginthreadex( NULL, 0, &ThreadedFunction, NULL, 0, &threadID ); hThread2 = (HANDLE)_beginthreadex( NULL, 0, &ThreadedFunction, NULL, 0, &threadID2 ); InitializeCriticalSection(&cs); // Wait until second thread terminates. If you comment out the line // below, Counter will not be correct because the thread has not // terminated, and Counter most likely has not been incremented to // 1000000 yet. //WaitForSingleObject( hThread, INFINITE ); //printf( "Counter should be 1000000; it is-> %dn", Counter ); system("pause"); // Destroy the thread object. CloseHandle( hThread ); CloseHandle( hThread2 ); DeleteCriticalSection(&cs); return 0; }
Linux pthread ¶
~cpp #include <stdio.h> #include <stdlib.h> #include <pthread.h> void *print_message_function( void *ptr ); int count= 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; main() { pthread_t thread1, thread2; char *message1 = "Thread 1"; char *message2 = "Thread 2"; int iret1, iret2; /* Create independent threads each of which will execute function */ iret1 = pthread_create( &thread1, NULL, print_message_function, (voi d*) message1); iret2 = pthread_create( &thread2, NULL, print_message_function, (voi d*) message2); /* Wait till threads are complete before main continues. Unless we */ /* wait we run the risk of executing an exit which will terminate */ /* the process and all threads before the threads have completed. */ pthread_join( thread1, NULL); pthread_join( thread2, NULL); printf("Thread 1 returns: %d\n",iret1); printf("Thread 2 returns: %d\n",iret2); exit(0); } void *print_message_function( void *ptr ) { char *message; message = (char *) ptr; while( count < 100000 ) { pthread_mutex_lock( &mutex ); count++; pthread_mutex_unlock( &mutex ); printf("%s: %d \n", message, count); } }