子线程给全局数组元素赋值
主线程在屏幕上打印出来,无限重复上述过程
事件
#include <windows.h>
#include<iostream>
using namespace std;
HANDLE hEvent1, hEvent2;
int a[ 5 ];
DWORD WINAPI Thread(PVOID pParams )
{ int i, num = 0;
while( TRUE )
{
WaitForSingleObject( hEvent2, INFINITE );
for ( i = 0; i < 5; i++ )
a[ i ] = num;
Sleep(100);
SetEvent( hEvent1 );
num++;
}
return 0;
}
int main()
{
hEvent1 = CreateEvent( NULL, FALSE, TRUE, NULL );
hEvent2 = CreateEvent( NULL, FALSE, FALSE, NULL );
CreateThread( NULL,0,Thread, NULL,0, NULL );
while( TRUE )
{
WaitForSingleObject( hEvent1, INFINITE );
cout<<a[ 0 ]<<" "<<a[ 1 ]<<" "<<a[ 2 ]<<" "<<a[ 3 ]<<" "<<a[ 4 ]<<endl;
Sleep(100);
SetEvent( hEvent2 );
}
return 0;
}
互斥量
#include <windows.h>
#include<iostream>
using namespace std;
HANDLE hMutex;
int a[ 5 ];
DWORD WINAPI Thread(PVOID pParams )
{ int i, num = 0;
while( TRUE )
{
WaitForSingleObject( hMutex, INFINITE );
for ( i = 0; i < 5; i++ )
a[ i ] = num;
Sleep(100);
ReleaseMutex( hMutex );
num++;
}
return 0;
}
int main()
{
hMutex = CreateMutex( NULL, FALSE, NULL );
CreateThread( NULL,0,Thread, NULL,0, NULL );
while( TRUE )
{
WaitForSingleObject( hMutex, INFINITE );
cout<<a[ 0 ]<<" "<<a[ 1 ]<<" "<<a[ 2 ]<<" "<<a[ 3 ]<<" "<<a[ 4 ]<<endl;
sleep(100);
ReleaseMutex( hMutex );
}
return 0;
}
临界区
#include "windows.h"
#include<iostream>
using namespace std;
CRITICAL_SECTION cs;
int a[ 5];
DWORD WINAPI Thread(PVOID pParams )
{ int i, num = 0;
while( TRUE )
{
EnterCriticalSection( &cs );
for ( i = 0; i < 5; i++ )
a[ i ] = num;
Sleep(100);
LeaveCriticalSection( &cs );
num++;
}
return 0;
}
int main()
{
InitializeCriticalSection( &cs );
CreateThread( NULL,0,Thread, NULL,0, NULL );
while( TRUE )
{
EnterCriticalSection( &cs );
cout<<a[ 0 ]<<" "<<a[ 1 ]<<" "<<a[ 2 ]<<" "<<a[ 3 ]<<" "<<a[ 4 ]<<endl;
Sleep(100);
LeaveCriticalSection( &cs );
}
return 0;
}