Trần Kim Dự
Trần Kim Dự

Reputation: 6102

C : pthread : value doesn't stay same in thread parameter

I try to test Linux pthread. I create multithread, in each thread, I pass some parameters through thread_arg struct. Before I pass to thread function, I print out, everything works fine. When this parameter passes to thread function, I print out again, I see that value in parameters doesn't stay as before.

Here is my code :

#include <pthread.h>
#include <unistd.h>
#include <stdio.h>

typedef struct  {
    int paramA;
    int paramB;
} thread_arg;

void* message(void* argObj) {
    thread_arg* arg = (thread_arg*) argObj;
    printf("Test2: %d &&& %d\n", arg->paramA, arg->paramB);
    return NULL;
}

void Func(int id, int num) {
    // run num-th thread.
    int i;
    for (i = 1; i <= num; i++) {
        // start a new thread
        pthread_t thread;
        // printf("thread with: %d and %d\n", id, i);
        // thread_arg arg = {.studentId = id, .questionId = i};
        thread_arg arg;
        arg.paramA = id;
        arg.paramB = i;
        printf("test 1: %d &&& %d\n", arg.paramA, arg.paramB);
        pthread_create(&thread, NULL, &message, &arg);
    }
}

int main() {
    int i;
  for(i=0;i<1;i++) {
    Func(i, 3);    
  } 
  while (1);
    return 0;
}

The result is :

test 1: 0 &&& 1  // normal
test 1: 0 &&& 2  // normal
test 1: 0 &&& 3  // normal
Test2: 0 &&& 3   // strange error
Test2: 0 &&& 3   // strange error
Test2: 0 &&& 3   // strange error

It's so strange, because three lines on test 2 should be contains all number 1 2 and 3.

I cannot explain why this situation happen. Please explain for me.

Thanks :)

Upvotes: 4

Views: 1659

Answers (1)

Greg Hewgill
Greg Hewgill

Reputation: 992847

When you create a new thread with pthread_create(), you pass the address of the arguments as &arg. This is just a pointer, and a pointer is all that your thread receives. When your Func() code loops around to start another thread, your arg variable goes out of scope and is destroyed. The memory previously occupied by arg is used for something else (probably the arg created for the next iteration of the loop).

One way to solve this is to allocate thread_arg *parg = (thread_arg *) malloc(sizeof thread_arg); and pass parg (a pointer) to pthread_create(). Don't forget to free the arguments within the thread after you're done with them.

Upvotes: 3

Related Questions