Click here to Skip to main content
15,888,108 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
The code working fine when removing comment from "pthread_exit(NULL)".
I am not getting it, why..??

C++
#include< stdio.h>
#include< pthread.h >
#include< stdlib.h >
#include< string.h >
#define N 200
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
char *n;
int i=1,comp=1;
void * read1()
{
    while(comp)
    {
        pthread_mutex_lock(&mutex);
        n=(char *)malloc(N*sizeof(char));
        printf("\nEnter a string:\t");
        gets(n);
        if((i=strcmp("end",n))==0)
            comp=0;
        pthread_mutex_unlock(&mutex);
        usleep(10);
    }}
void * write1()
{
    while(comp)
    {
        usleep(50);
        pthread_mutex_lock(&mutex);
        if(i!=0)
            printf("\nThe string entered is : %s\n",n);
        pthread_mutex_unlock(&mutex);
    }}
int main()
{
    pthread_t tr, tw;
    int res;
    pthread_mutexattr_t attr;
    pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE);
    res=pthread_mutex_init(&mutex,&attr);
    pthread_create(&tr,NULL,read1,NULL);
    pthread_create(&tw,NULL,write1,NULL);
    //pthread_exit(NULL);
    return 0;
}
Posted
Updated 13-Oct-13 5:37am
v2

1 solution

The main() function is called/executed by the runtime library. The runtime lib does the following when you start your program:
1. Initialization of the runtime library
2. Initialization of global variables in your program
3. calling main() of your program
4. Destroying the global variables in your program
5. Deinitialization of the runtime library
6. Process termination.

If you exit your main thread without returning from your main() function then the steps 4, 5, and 6 will never be executed and your program terminates when all threads exit. (Note that killing/terminating the main thread is not the same as terminating/killing the process! (...but this can be platform specific.)) If you don't call pthread_exit(NULL) from your main thread then steps 4, 5, and 6 will be executed and step 6 kills your process no matter what is the progress of your worker threads. The correct solution is not to kill your main thread with pthread_exit(NULL) but joining both worker threads (to wait for their termination) before returning from main.

(Side note: step 4, 5 and 6 get executed not only if you return from main but also if you call the exit() function of the runtime library.)
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 13-Oct-13 20:20pm    
5ed.
—SA
pasztorpisti 14-Oct-13 4:19am    
Thank you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900