PDA

View Full Version : semaphore functions



pthread
11-14-2006, 10:35 PM
this is my c code regarding threads ....


#include<stdio.h>
#include<pthread.h>
//#include<semaphores.h>


void *function1()
{
printf("thread numbers(1-10): %ld\n",pthread_self());
}

void *function2()
{
printf("thread number 11 : %ld\n",pthread_self());
}

int main()
{
int i;
pthread_t thread[10],thread11;
for(i=0;i<10;i++)
{
pthread_create(&thread[i],NULL,&function1,NULL);
}
pthread_create(&thread11,NULL,&function2,NULL);
}


thread 11 should execute after all the 10 threads have completed their process

i want to use semaphore fuctions instead thread_join ...... can anyone help

in implementing this.....


thanks in advance..

pthread

sl4nted
11-15-2006, 01:31 AM
#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

pthread
11-15-2006, 02:27 AM
thanx sl4nted.......

pthread
11-15-2006, 02:55 AM
is there any other solution for that code ..... is it possible by using sem_wait ,sem_post,sem_init functions .....


thanx

pthread