How do I get threads to execute properly

时间:2018-02-03 07:39:11

标签: c pthreads

I am writing a c program using pthreads on ubuntu linux platform. I have created a child process and I want this child process to create multiple threads that will do certain things concurrently and for that I have written this code given below.

int main(){
    initialize();
    int pid;
    pid=fork();
    if(pid<0)
    {
        printf("\n Error ");
        exit(1);
    }
    else if(pid==0)
    {
        printf("Hello I am child process\n"); 
        pthread_t t1,t2;

        pthread_create(&t1,NULL,say_hello,"hello from 1");
        pthread_create(&t2,NULL,say_hi,"hi from 2");
        //exit(0);
    }
    else
    {
        printf("\n Hello I am the parent process ");
        printf("\n My actual pid is %d \n ",getpid());
        //exit(1);
    }
    return c;
}`

void* say_hello(void* data){
    char *str;
    str = (char*)data;    
    while(1){
        printf("%s\n",str);
        sleep(1);
    }
}

void* say_hi(void* data){
    char *str;
    str = (char*)data;
    while(1){
        printf("%s\n",str);
        sleep(1);
    }
}

I was expecting output like first the printf statement of child process will execute and then two threads will keep on executing concurrently execting "hello from 1" and "hi from 2" simultaneouly until ctrl+c is pressed. But after executing the printf statment it only executes either threads only one or two times at then program terminates. How do I get proper behaviour of this program?

2 个答案:

答案 0 :(得分:2)

In the child process, the main thread exits immediately (by returning from main()). When this happens, the entire process is terminated, including other threads.

There is a separate pthread_exit() function which only exits one particular thread. This can be used on the main thread; using this method, other threads can continue running.

答案 1 :(得分:0)

This happens because the parent that creates the threads terminates, as the main() function returns. As it exits, the thread exits too. To prevent the programm to exit before a thread has completed his routine you can use pthread_join() function.

For exemple, in your case, after using pthread_create(), using pthread_join() on the first thread you created will block the father untill your first thread is done doing his job. Try this:

 pthread_create(&t1,NULL,say_hello,"hello from 1");
 //your second pthread_create
 pthread_join(th1, NULL);