Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthread creation not working properly

Tags:

c

pthreads

i have this piece of code:

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

int number;
pthread_mutex_t  *mutex;
pthread_t *threads;

void *PrintHello(void *threadid)
{
    long tid;
    tid = (long)threadid;
    printf("Hello World! It's me, thread #%ld!\n", tid);
    time_t rawtime;
    struct tm * time_start;
    time ( &rawtime );
    time_start = localtime ( &rawtime );
    printf ( "The number %ld thread is created at time %s  \n",tid, asctime     (time_start));
    pthread_exit(NULL);
}

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

    printf("give threads");
    scanf("%d",&number);
    mutex = calloc( number, sizeof(*mutex));
    threads = calloc(number, sizeof(*threads));

    for (i = 0; i < number;i++) {
        pthread_mutex_init( &mutex[i],NULL);
    }

    for(i=0; i<number; i++){
        printf("In main: creating thread %d\n", i);
        rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i);
        if (rc){
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(-1);
        }
    }

    return 0;
}

The purpose of this code is to ask the user to give the number of the threads that it is going to create and after the creation of the threads,the thread itself will print 2 messages saying the number of the thread and the time that it was created.

The problem is that inside the main the message "In main: creating thread" is showing up but the message inside the threads sometimes does not.

For example, it would create 3 threads and only 1 thread will show up its message and that thread also will not show up the time that was created. I dont know if there is something wrong with the code.

like image 677
Izanagi Avatar asked Apr 22 '26 05:04

Izanagi


1 Answers

Root Cause:
Your main() exits before the child threads get an opportunity to complete their task.

Solution:
You need to make sure that the main() waits until all the threads have completed their work.
You need to use:

pthread_join()

to achieve this functionality. Add the following before returning from main():

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

Other problems:

  • You allocate memory dynamically but never deallocate it. Eventhough, the OS reclaims the memory once your program returns. It is a good practice to do so explicitly.
  • You created a mutex but you neither use it, nor deallocate it. But that seems to be code in progress.
like image 151
Alok Save Avatar answered Apr 24 '26 18:04

Alok Save