Code:
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
};
int semset_id; /*set id*/
struct sembuf sem_op; /*struct for operations*/
void *function1(void *arg)
{
printf("thread numbers(1-10)\n");
/* increase semaphore counter */
sem_op.sem_num = 0;
sem_op.sem_op = 1;
sem_op.sem_flg = 0;
semop(semset_id, &sem_op, 1);
pthread_exit(NULL);
}
void *function2(void *arg)
{
/* wait till semaphore value is 10 */
sem_op.sem_num = 0;
sem_op.sem_op = -10;
sem_op.sem_flg = 0;
semop(semset_id, &sem_op, 1);
printf("thread number 11\n");
pthread_exit(NULL);
}
int main()
{
int i;
pthread_t thread[10],thread11;
union semun sem_val; /* sem value */
void *ret_val;
semset_id = semget(IPC_PRIVATE, 1, 0600); /* create set */
if (semset_id == -1)
{
perror("Crap");
exit(1);
}
sem_val.val = 0;
semctl(semset_id, 0, SETVAL, sem_val);
if (pthread_create(&thread11,NULL,function2,NULL) != 0)
{
perror("Create 11");
exit(1);
}
for(i=0;i<10;i++)
{
if (pthread_create(&thread[i],NULL,function1,NULL) != 0)
{
perror("Create");
exit(1);
}
}
for (i = 0; i < 10; i++)
pthread_join(thread[i], &ret_val);
pthread_join(thread11, &ret_val);
return 1;
}
theres probably a better way to do this, I haven't used semaphores for awhile (maybe without the globals), but this does work
so should get you on the way
output:
thread numbers(1-10)
thread numbers(1-10)
thread numbers(1-10)
thread numbers(1-10)
thread numbers(1-10)
thread numbers(1-10)
thread numbers(1-10)
thread numbers(1-10)
thread numbers(1-10)
thread numbers(1-10)
thread number 11
whether the 11th is created before the other 10 or after