Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

How to find out which thread is running and how to use semaphores in C

I'm doing a program where an input is given by the user for the number of tickets and the number of sellers.I have an array of threads, the number of the threads equal to the number of sellers. I have to "sell" tickets by using a sell function for all the threads. I have to use counting semaphores to see how many tickets I have left and how many each thread sells.

The output would look something like this Seller #1 sold one (49 left) Seller #0 sold one (48 left) Seller #1 sold one (47 left) Seller#1 sold one (46 left) Seller #1 sold one (45 left) Seller #1 sold one (44 left) Seller #1 sold one (43 left) Seller #2 sold one (42 left).. and so on

I'm having trouble finding out which seller (thread) is which and how to do the semaphores correctly. Any suggestions?

so far I have this

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>

sem_t sem1;

void *sell(void* ticks){
    int num_tickets = *(int*)ticks; //how many tickets each seller sold
    int i;
    int tickets_sold;
    printf("The total number of tickets are: %d\n", num_tickets);
    for(i = 0; num_tickets > 0; i++){

        sem_post(&sem1);
        num_tickets = num_tickets - 1;
        sem_wait(&sem1);


        tickets_sold++;
        printf("Seller sold (%d)\n", tickets_sold);
    }

    return NULL;
}



int main(int argc, char *argv[]){

    if (argc != 3){
        fprintf(stderr, "usage: a.out<integer value>\n");
        return -1;
    }

    if (atoi(argv[1]) < 0){
        fprintf(stderr,"Argument %d must be non-negative\n", atoi(argv[1]));
        return -1;
    }

    if (atoi(argv[2]) < 0){
        fprintf(stderr,"Argument %d must be non-negative\n", atoi(argv[1]));
        return -1;
    }

    else{

        int total_ticks= atoi(argv[1]);
        int num_sellers = atoi(argv[2]);
        int i;
        sem_init(&sem1, 0, total_ticks);


        pthread_t threads[num_sellers]; 

        for(i = 0; i < num_sellers; i++){

            pthread_create(&threads[i], NULL, sell, (void*) &total_ticks);
        }


    pthread_exit(0);
    return 0;

    }
}

Comments