Hello,
I have an issue with threads.
I am defining a global variable, a char * that I initialize to NULL, and a mutex.
pthread_mutex_t mutex;
char *minURLTime;
minURLTime = NULL;
Then I initialize my mutex:
pthread_mutex_init(&mutex, NULL);
I then create a new thread:
void *status;
pthread_t t;
pthread_create(&t, NULL, executeThread, (void *) &val);
pthread_join(t, &status);
And inside that function I allocate space for minURLTime using strdup and copy a string from link:
pthread_mutex_lock(&mutex);
minURLTime = strdup(link);
pthread_mutex_unlock(&mutex);
As I am using the heap (through strdup, which calls malloc), I do not understand why minURLTime is not NULL until the thread is exited, but then it is NULL.
pthread_exit(NULL);
Once pthread_exit is called, although minURLTime is a global variable that was allocated through strdup (which calls malloc), it appears to be NULL. I don't understand, could anyone please explain me?
Thank you very much,
EDIT:
A little more detail.
From main():
void *status;
pthread_t t;
pthread_create(&t, NULL, executeThread, (void *) &val);
pthread_join(t, &status);
ExecuteThread function:
void *
executeThread( void *val )
{
executeRequest(*((int *) val));
if (minURLTime != NULL) {
pthread_mutex_lock(&mutex);
fprintf(stderr, "\nURL AFTER THREAD ( BEFORE EXIT ): %s\n", minURLTime); // Not executed
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
fprintf does not get executed (BEFORE returning pthread_exit).
executeRequest Function:
void
executeRequest( int val )
{
/* some code */
pthread_mutex_lock(&mutex);
minURLTime = strdup(link);
pthread_mutex_unlock(&mutex);
if (minURLTime != NULL) {
pthread_mutex_lock(&mutex);
fprintf(stderr, "\nURL: %s\n", minURLTime); // This one DOES print
pthread_mutex_unlock(&mutex);
}
}
This may be helpful. It prints inside executeRequest, but not inside executeThread, before the thread exited.
Jary