pthread_join的使用注意
pthread_join
在Linux中,新建的线程并不是在原先的进程中,而是系统通过一个系统调用clone()。该系统copy了一个和原先进程完全一样的进程,并在这个进程中执行线程函数。不过这个copy过程和fork不一样。 copy后的进程和原先的进程共享了所有的变量,运行环境。这样,原先进程中的变量变动在copy后的进程中便能体现出来。
回收时子线程资源避免回收局部变量
正确回收方法一
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
struct test_st
{
int val;
char str[10];
};
void *tid_cb(void *arg)
{
struct test_st *tval;
tval = malloc(sizeof(tval));
tval->val = 100;
strcpy(tval->str, "hello world");
return (void *)tval;
}
int main()
{
pthread_t tid;
int ret = pthread_create(&tid, NULL, tid_cb, NULL);
if (ret != 0)
{
fprintf(stderr, "pthread_create: %s\n", strerror(ret));
}
struct test_st *retval;
ret = pthread_join(tid, (void **)&retval);
if (ret != 0)
{
fprintf(stderr, "pthread_join: %s\n", strerror(ret));
}
printf("child thread exit with val=%d,str=%s\n", retval->val, retval->str);
pthread_exit(NULL);
return 0;
}
正确回收方法二
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
struct test_st
{
int val;
char str[10];
};
void *tid_cb(void *arg)
{
struct test_st *tval = (struct test_st *)arg;
tval = malloc(sizeof(tval));
tval->val = 100;
strcpy(tval->str, "hello world");
return (void *)tval;
}
int main()
{
pthread_t tid;
struct test_st *retval;
struct test_st arg;
int ret = pthread_create(&tid, NULL, tid_cb, (void *)&arg);
if (ret != 0)
{
fprintf(stderr, "pthread_create: %s\n", strerror(ret));
}
ret = pthread_join(tid, (void **)&retval);
if (ret != 0)
{
fprintf(stderr, "pthread_join: %s\n", strerror(ret));
}
printf("child thread exit with val=%d,str=%s\n", retval->val, retval->str);
pthread_exit(NULL);
return 0;
}
输出:child thread exit with val=100,str=hello world
错误写法:子线程中的局部变量作为回收值,此时会出现段错误
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
struct test_st
{
int val;
char str[10];
};
void *tid_cb(void *arg)
{
struct test_st *tval;
tval = malloc(sizeof(tval));
tval->val = 100;
strcpy(tval->str, "hello world");
return (void *)tval;
}
void *tid_cb1(void *arg){
int pval=100;
return (void*)pval;
}
int main()
{
pthread_t tid;
int ret = pthread_create(&tid, NULL, tid_cb1, NULL);
//struct test_st *retval;
int *retval;
pthread_join(tid, (void **)&retval);
//printf("child thread exit with val=%d,str=%s\n", retval->val, retval->str);
printf("child thread exit with val=%d ",*retval);
pthread_exit(NULL);
return 0;
}