Για να το πετύχω αυτό ´εγραψα τον εξής κώδικα:
- Κώδικας: Επιλογή όλων
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<semaphore.h>
#define NUMTHREADS 10
#define NUMUTHREADS2 45
void * myThread();
void * mythread3();
void * myThread2();
int counter=0,times=0;
sem_t s1,s2,s3,e1,e2;
char *c="Hello";
void * myThread()
{
sem_wait(&s1);
counter++;
if(counter==NUMTHREADS)
{
sem_post(&e1);
printf("MYthread semaphore un;locked\n");
}
sem_post(&s1);
pthread_exit(NULL);
}
void * mythread3()
{
int rc;
sem_wait(&e2);
sem_wait(&s3);
printf("mythread3 %d\n",times);
sem_post(&s3);
pthread_exit(NULL);
}
void * myThread2()
{
sem_wait(&e1);
sem_wait(&s2);
times++;
printf("myThread2 times %d\n",times);
if(times==NUMUTHREADS2)
{
sem_post(&e2);
printf("Mytghread semaphore2 unlocked\n");
}
sem_post(&s2);
pthread_exit(NULL);
}
int main()
{
int i,rc;
pthread_t threads[NUMTHREADS],threads2[NUMUTHREADS2],threads3[NUMTHREADS];//each table is a group of thread
/*initializing semaphhores*/
sem_init(&s1, 0, 1);
sem_init(&s2,0,1);
sem_init(&s3,0,1);
sem_init(&e1,0,1);
sem_init(&e2,0,1);
for(i=0;i<NUMTHREADS;i++)//creating 1st group of threads
{
rc=pthread_create(&threads[i],NULL,myThread,NULL);
}
if(rc)//checking for errors
{
fprintf(stderr,"ERROR");
exit(-1);
}
for(i=0;i<NUMUTHREADS2;i++)//creating second group of threads
{
rc=pthread_create(&threads2[i],NULL,myThread2,NULL);
}
if(rc)
{
fprintf(stderr,"ERROR");
exit(-1);
}
for(i=0;i<NUMTHREADS;i++)//creating trhird group of threads
{
rc=pthread_create(&threads3[i],NULL,mythread3,NULL);
}
if(rc)//checking for errors
{
fprintf(stderr,"ERROR");
exit(-1);
}
for(i=0;i<NUMTHREADS;i++)//joining first group of threads
{
pthread_join(threads[i],NULL);
}
for(i=0;i<NUMUTHREADS2;i++)//here for second one
{
pthread_join(threads2[i],NULL);
}
for(i=0;i<NUMTHREADS;i++)//here for third one
{
pthread_join(threads3[i],NULL);
}
printf("counter has value %d\n",counter);
/*destroying semaphores */
sem_destroy(&s1);
sem_destroy(&s2);
sem_destroy(&s3);
sem_destroy(&e1);
sem_destroy(&e2);
}
Όμως δεν μπορώ να πετύχω αυτό όπου θέλω όπως θα δείτε και στο παρακάτω παράδειγμα εκτέλεσης
- Κώδικας: Επιλογή όλων
pcmagas@pcmagas-Inspiron-1010:~/Kwdikas/C/Diergasies/Ergasia$ ./TestmyThread2 times 1
mythread3 1
MYthread semaphore un;locked
myThread2 times 2
Μετά την τελευτάια γραμμή της εκτέλεσης κολλάει. Και το thread3 δεν κάνει ότι προέβλεψα (Πρέπει να εκτυπώνει την τιμή 45)
Έχεται καμιά ιοδέα πως να το πετύχω αυτό?