题目:创建一个线程,并理清主线程结束时会发生什么。
代码:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h> void func()
{
fprintf(stderr, "Thread has been created!\n");
return;
} int main()
{
pthread_t tid;
printf("Create thread1...\n");
pthread_create(&tid, NULL, (void*)func, NULL);
printf("main() begin sleep...\n");
sleep(5); // 防止父进程退出导致线程结束,而使得其调用函数无法执行
printf("main() end sleep...\n");
return 0;
}
题目:创建一个线程,并使用join函数等待线程结束。
完成代码:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h> void func()
{
fprintf(stderr, "Thread has been created!\n");
pthread_exit(NULL);
return;
} int main()
{
pthread_t tid;
printf("Create thread1...\n");
pthread_create(&tid, NULL, (void*)func, NULL);
pthread_join(tid, NULL);
return 0;
}
题目:使用join函数完成传值功能。
完成代码:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h> int retVal;
void func()
{
retVal = 99;
fprintf(stderr, "Thread has been created!\n");
pthread_exit(&retVal);
} int main()
{
pthread_t tid;
printf("Create thread1...\n");
pthread_create(&tid, NULL, (void*)func, NULL);
int *pRet;
pthread_join(tid, (void*)&pRet);
printf("retVal is %d\n", *pRet);
return 0;
}