简体   繁体   中英

thread exit discrepency in multi-thread scenario

I have written a very simple code for practicing semaphore. Task is to sell tickets and each thread should update the shared variable of total tickets till it becomes zero. Issue I am observing is - the thread which sells last ticket and makes ticket_count = 0 by decrementing it exits without printing how many total tickets it sold. I added mutex around printf just for hack of it as I read about issues of printf in multi-threaded environment on SO. Reason I find this issue different than normal printf issues pointed at SO with regard to multi-threading is - its always ( not always 8/10 times - issue is intermittent - other 2 times it prints all 4 threads ticket sold) the last thread ie the one which sells last ticket skips the printf and exits. Can someone point me what am I doing wrong ?

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

#define NUMTHREADS  4       /* number of threads i.e. ticket sellers */

static unsigned int ticket_count = 25;

pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;

sem_t mutex;

void *ticketProcessing(void *arg)
{
    bool loop_alive = true;
    int local_counter = 0;
    while(loop_alive)
    {
        sleep(1);
        sem_wait(&mutex);
        if (ticket_count > 0)
        {
            local_counter++;
            ticket_count--;
            printf(" thread id -- %d - decided to sell 1 ticket \n ", (int)pthread_self());
        }
        else
        {
            loop_alive = false;
        }
        sem_post(&mutex);
    }

    pthread_mutex_lock(&mutex2);
    printf(" ticket sold by thread id -- %d -- is  %d \n ", (int)pthread_self(), local_counter);
    pthread_mutex_unlock(&mutex2);
  //  return 0;
}

int main(void)
{
    pthread_t sellingTicket;
    sem_init(&mutex, 0, 1);
    int i;

    for(i = 0; i < NUMTHREADS; i++)
    {
        pthread_create(&sellingTicket, NULL, ticketProcessing, NULL);
    }

    i = 0;
    while(i < NUMTHREADS)
    {
        pthread_join(sellingTicket, NULL);
        i++;
    }


    printf(" All threads exited !!! \n ");
    return 0;
}

Edit : I tried to create array and join in below fashion and it works

 pthread_t threads[4];

 for(i = 0; i < 4; i++)
 {
     pthread_create(&threads[i], NULL, ticketProcessing, NULL);
 }

for(i = 0; i < 4; i++)
{
    pthread_join(threads[i], NULL);
}

Your join loop tries to join the last thread over and over rather than trying to join each thread that was created. You need to keep track of the thread IDs so that you can join them all.

Once you've joined a thread, the thread ID is invalid and it is a serious mistake to pass it to any pthread_* function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM