83 lines
1.8 KiB
C
83 lines
1.8 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <time.h>
|
|
#include <pthread.h>
|
|
#include <unistd.h>
|
|
#include <sys/types.h>
|
|
#include <sys/ipc.h>
|
|
#include <sys/sem.h>
|
|
|
|
|
|
//~ HANDLE hEvent1, hEvent2;
|
|
int key = 0x20; // Semaphore key
|
|
|
|
int a[ 5 ];
|
|
|
|
void Thread( void* pParams )
|
|
{
|
|
// Thread 2
|
|
struct sembuf operation[1] ;
|
|
|
|
// open semaphore
|
|
int mysemid = semget(key, 2, 0);
|
|
|
|
operation[0].sem_op = 1; // Release on the second resource
|
|
operation[0].sem_num = 1;
|
|
operation[0].sem_flg = SEM_UNDO;
|
|
|
|
//Release semaphore 2
|
|
semop(mysemid, operation, 1);
|
|
|
|
int i, num = 0;
|
|
|
|
while ( 1==1 )
|
|
{
|
|
WaitForSingleObject( hEvent2, INFINITE );
|
|
for ( i = 0; i < 5; i++ ) a[ i ] = num;
|
|
SetEvent( hEvent1 );
|
|
num++;
|
|
}
|
|
}
|
|
|
|
int main( void )
|
|
{
|
|
// Thread 1
|
|
struct sembuf operation[2] ;
|
|
|
|
// Create 2 semaphores
|
|
semid = semget(key, 2, 0666 | IPC_CREAT);
|
|
|
|
|
|
operation[0].sem_op = 1; //Release first resource
|
|
operation[0].sem_num = 0;
|
|
operation[0].sem_flg = SEM_UNDO;
|
|
|
|
operation[0].sem_op = -1; // Wait on the second resource
|
|
operation[0].sem_num = 1;
|
|
operation[0].sem_flg = SEM_UNDO;
|
|
|
|
//Release semaphore 1 and wait on semaphore 2
|
|
// note : thread is suspended until the semaphore 2 is released.
|
|
semop(semid, operation, 2);
|
|
|
|
// thread is released
|
|
// delete the semaphore
|
|
semctl(semid, 0, IPC_RMID , 0)
|
|
|
|
hEvent1 = CreateEvent( NULL, FALSE, TRUE, NULL );
|
|
hEvent2 = CreateEvent( NULL, FALSE, FALSE, NULL );
|
|
|
|
_beginthread( Thread, 0, NULL );
|
|
|
|
while( 1==1 )
|
|
{
|
|
WaitForSingleObject( hEvent1, INFINITE );
|
|
printf( "%d %d %d %d %d\n",
|
|
a[ 0 ], a[ 1 ], a[ 2 ],
|
|
a[ 3 ], a[ 4 ] );
|
|
SetEvent( hEvent2 );
|
|
}
|
|
return 0;
|
|
}
|
|
|