1.使用临界区(Critical Section Objects)
任一时刻只有一个线程可以拥有临界区对象,拥有临界区的线程可以访问被保护起来的资源或代码段,其他希望进入临界区的线程将被挂起等待,直到拥有临界区的线程放弃临界区时为止,这样就保证了不会在同一时刻出现多个线程访问共享资源。
const int ARRAY_SIZE = 5;
int g_IntArray[ARRAY_SIZE];
CRITICAL_SECTION g_criticalSection;
void SimpleThread(void *pParam)
{
int num(10);
while(num > 0)
{
::EnterCriticalSection(&g_criticalSection);
for (int i = 0;i < ARRAY_SIZE; ++i)
{
g_IntArray[i] = num;
cout<<g_IntArray[i]<<" ";
}
cout<<endl;
num--;
::LeaveCriticalSection(&g_criticalSection);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
::InitializeCriticalSection(&g_criticalSection);
_beginthread(SimpleThread,0,NULL);
int n = 10;
while(n > 0)
{
::EnterCriticalSection(&g_criticalSection);
for (int i = 0; i < ARRAY_SIZE; ++i)
{
cout<<g_IntArray[i]<<" ";
}
cout<<endl;
n--;
::LeaveCriticalSection(&g_criticalSection);
}
}
2.互斥对象(Mutex Objects)
互斥对象与临界区对象很像.互斥对象与临界区对象的不同在于:互斥对象可以在进程间使用,而临界区对象只能在同一进程的各线程间使用。当然,互斥对象也可以用于同一进程的各个线程间,但是在这种情况下,使用临界区会更节省系统资源,更有效率。
HANDLE g_hMutex;
void SimpleThread2(void *pParam)
{
int num(0);
while (num<100)
{
::WaitForSingleObject(g_hMutex, INFINITE);
for ( int i = 0; i < ARRAY_SIZE; ++i )
{
g_IntArray[i] = num;
cout<<"sub thread"<<endl;
cout<<g_IntArray[i]<<" ";
}
::ReleaseMutex(g_hMutex);
num++;
cout<<endl;
}
}
int main()
{
g_hMutex = ::CreateMutex(NULL, FALSE, NULL);
::_beginthread(SimpleThread2, 0, NULL);
while (true)
{
::WaitForSingleObject(g_hMutex, INFINITE);
for ( int i = 0; i < ARRAY_SIZE; ++i )
{
cout<<"main thread"<<endl;
cout<<g_IntArray[i]<<" ";
}
::ReleaseMutex(g_hMutex);
cout<<endl;
}
}
3.事件(Event)
事件是一个允许一个线程在某种情况发生时,唤醒另外一个线程的同步对象。
HANDLE g_hEvent1, g_hEvent2;
unsigned __stdcall SimpleThread3(void* pParam)
{
//int count = (int)pParam;
int count = 10;
int num(0);
while (count--)
{
::WaitForSingleObject(g_hEvent1, INFINITE);
for ( int i = 0; i < ARRAY_SIZE; ++i )
{
g_IntArray[i] = num;
cout<<"sub thread"<<endl;
cout<<g_IntArray[i]<<" ";
}
::SetEvent(g_hEvent2);
num++;
cout<<endl;
}
return 0;
}
int main()
{
g_hEvent1 = ::CreateEvent(NULL, FALSE, TRUE, NULL);
g_hEvent2 = ::CreateEvent(NULL, FALSE, FALSE, NULL);
int count(10);
HANDLE hThread = (HANDLE)::_beginthreadex(NULL, 0, SimpleThread3, &count, 0, NULL);
if ( NULL == hThread )
{
cout<<"_beginthreadex failed. errno: "<<errno<<endl;
return 1;
}
while (count--)
{
::WaitForSingleObject(g_hEvent2, INFINITE);
for ( int i = 0; i < ARRAY_SIZE; ++i )
{
cout<<"main thread"<<endl;
cout<<g_IntArray[i]<<" ";
}
::SetEvent(g_hEvent1);
cout<<endl;
}
// NOTE: The system closes the handle automatically when the process terminates.
::CloseHandle(hThread);
::CloseHandle(g_hEvent2);
::CloseHandle(g_hEvent1);
}