开发者

Issue with threads: value stored in heap

开发者 https://www.devze.com 2023-01-20 00:56 出处:网络
I have an issue with threads. I am defining a global variable, a char * that I initialize to NULL, and a mutex.

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 = NU开发者_StackOverflowLL;

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


You aren't waiting in the main thread for the new thread to complete, so you're seeing the null before the thread gets around to setting something else. Also, since you haven't protected the variable with a lock, or declared it volatile, the compiler might even have optimized out noticing that the thread changed it.


My apologies, I realize what the problem was, it was something inside executeRequest that was messing up with those variables, I really don't know how it could have overwritten exactly THAT part of memory, but it is fixed. Thank you and sorry!

0

精彩评论

暂无评论...
验证码 换一张
取 消