Izanagi
Izanagi

Reputation: 526

pthread creation not working properly

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.

Upvotes: 2

Views: 11883

Answers (2)

Alok Save
Alok Save

Reputation: 206616

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.

Upvotes: 12

Anton Kovalenko
Anton Kovalenko

Reputation: 21517

Return from main() is equivalent to calling exit(...), which terminates the whole process. You may use pthread_join() to wait for each non-main thread, like another answer advises, or you may call pthread_exit(NULL) in the end of your main(): it would exit the initial thread, but other threads will continue to run.

Upvotes: 3

Related Questions