1

good morning, i try to execute 2 threads t1 and t2 by using the semaphore c library. I wrote this code

#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
#define Max 100;
int cpt=0;
sem_t mutex;
void* count(void* data)
{
    int i;
    sem_wait(&mutex);
    printf("thread %d enter in critical section\n",
    data);
    for (i=0;i<100;i++)
    {
        printf("Thread %d: Counter Value: %d\n", data, cpt);
        cpt++;
        printf(" thread %d modify the counter %d\n",data,cpt);

    }
    printf("thread %d exit critical section \n",
    data);
    sem_post(&mutex);
    pthread_exit(NULL);

}
int main()
{
    pthread_t t1,t2;
    sem_init(&mutex,0,1);// binary semaphore
    pthread_create(&t1, NULL, count, (void*)1); 
    pthread_create(&t2, NULL, count, (void*)2); 
    pthread_join(t1, NULL);
    pthread_join(t2, NULL); 
    sem_destroy(&mutex);
    printf("Compteur: %d\n", cpt);


}

the code work without bugs but i got 2 threads whose enter in the critical section, i would like that the first thread show the 100 values and the thread 2 continue the other values until 200.

  • you can join t1 before starting t2 to do so, but doing this destroys concurrency and your program will act just like a sequential program. – monster Jun 28 '17 at 12:03

0 Answers0