Linux c多线程编程时创建线程的函数:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
给子线程传递参数要通过void *类型的arg参数,大多传递参数都是传递参数的地址例如:
-
void *thread_func(void *arg)
-
{
-
int value = *(int*)arg;
-
return (void *)0;
-
}
-
-
int value;
-
pthread_t pid = pthread_create(&pid, NULL, thread_func, &value);
但当value值会改变时,传递给thread_func的值可能就不是先前的值.
要避免参数改变,可以采取的一种方法是函数参数改为值传递,例如:
-
void *thread_func(void *arg)
-
{
-
int value = (int)arg;
-
}
-
-
int value;
-
-
pthread_t pid = pthread_create(&pid, NULL, thread_func, (void*)value);
阅读(1403) | 评论(0) | 转发(0) |