dev/cpp/multithreading/mutexes.c

50 lines
1.0 KiB
C
Raw Normal View History

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
//~ CRITICAL_SECTION cs;
pthread_mutex_t mutex; // Mutex
int a[ 5 ];
void *Thread( void* pParams )
{
int i, num = 0;
while ( 1==1 )
{
//~ EnterCriticalSection( &cs );
pthread_mutex_lock(&mutex);
for ( i = 0; i < 5; i++ ) a[ i ] = num;
//~ LeaveCriticalSection( &cs );
pthread_mutex_unlock(&mutex);
num++;
}
}
int main( void )
{
//~ InitializeCriticalSection( &cs );
pthread_mutex_init(&mutex,NULL);
//~ _beginthread( Thread, 0, NULL );
pthread_t tr;
if(pthread_create(&tr,NULL,Thread,NULL) != 0)
return EXIT_FAILURE;
while( 1==1 )
{
//~ EnterCriticalSection( &cs );
pthread_mutex_lock(&mutex);
printf( "%d %d %d %d %d\n",
a[ 0 ], a[ 1 ], a[ 2 ],
a[ 3 ], a[ 4 ] );
//~ LeaveCriticalSection( &cs );
pthread_mutex_unlock(&mutex);
}
return 0;
}