-
Trouble pthread_create
I have NetBSD on i386. I am using the GNU pthread library. When I run the following code, the same integer value is printed in both func1 and func2. The value 89 is printed in both functions.
Code:
#include <pthread.h>
void func1(void *n)
{
int *a = (int *) n;
printf("hello: %i\n", *a);
}
void func2(void *r)
{
int *b = (int *) r;
printf("hello again: %i\n", *b);
}
void make_thread(pthread_t *thread, void (*func)(void *), int value)
{
printf("value: %i\n", value);
pthread_create(thread, NULL, (void *) (func), &value);
}
int main()
{
int *retval;
pthread_t thread1, thread2;
make_thread(&thread1, &func1, 34);
make_thread(&thread2, &func2, 89);
pthread_join(thread1, (void **) &retval);
pthread_join(thread2, (void **) &retval);
return 0;
}
Thanks.
-
I rewrote the code so the compiler won't give me a warning.
Code:
#include <pthread.h>
void *func1(void *n)
{
int *a = (int *) n;
printf("hello: %i\n", *a);
return NULL;
}
void *func2(void *r)
{
int *b = (int *) r;
printf("hello again: %i\n", *b);
return NULL;
}
void make_thread(pthread_t *thread, void* (*func)(void *), int value)
{
pthread_create(thread, NULL, func, (void *) &value);
}
int main()
{
int *retval;
pthread_t thread1, thread2;
make_thread(&thread1, &func1, 34);
make_thread(&thread2, &func2, 89);
pthread_join(thread1, (void **) &retval);
pthread_join(thread2, (void **) &retval);
return 0;
}
When I run on NetBSD I get the following results:
hello: 89
hello again: 89
But when I run of IRIX 6.5, I get the following:
hello: 2147430336
hello again: 2147430336
-
> pthread_create(thread, NULL, func, (void *) &value);
You're passing a pointer to a local variable - which goes out of scope the moment the function exits, and which is therefore no longer valid when you dereference it in your thread.
-
Thanks
Then how else would I do it?
-
> Then how else would I do it?
The pointer you pass to pthread_create() has to last up to the pthread_join() call.
In your case, this means
- a local var in main()
- a global variable
- a pointer returned from malloc()
-
Ok, here's what I did, and it worked:
Code:
include <pthread.h>
void *func1(void *n)
{
int *a = (int *) n;
printf("hello: %i\n", *a);
return NULL;
}
void *func2(void *r)
{
int *b = (int *) r;
printf("hello again: %i\n", *b);
return NULL;
}
void make_thread(pthread_t *thread, void* (*func)(void *), int *value)
{
pthread_create(thread, NULL, func, value);
}
int main()
{
int *retval, i = 34, j = 89;
pthread_t thread1, thread2;
make_thread(&thread1, &func1, &i);
make_thread(&thread2, &func2, &j);
pthread_join(thread1, (void **) &retval);
pthread_join(thread2, (void **) &retval);
return 0;
}
Thanks.