pthread_creat 函数 int pthread_create(pthread_t * tidp, const pthread_attr_t *attr, void (start_rtn)(void *), void *arg);
用来创建一个线程,返回:成功返回0,出错返回错误编号。当pthread_create 函数返回成功时。有tidp指向的内存被设置为新创建线程的线程ID 。
pthread_join 函数int pthread_join(pthread_t thread, void **rval_ptr);
返回:成功返回0,出错返回错误代码thread是目标线程标识符,rval_ptr指向目标线程返回时的退出信息,该函数会一直堵塞。直到被回收的线程结束为止。
pthread_exit 线程终止函数,void pthread_exit(void *rval_ptr);
线程在结束时最好调用该函数。以确保安全、干净的退出。pthread_exit函数通过rval_ptr參数向调用线程的回收者传递退出信息。进程中的其它线程能够调用pthread_join函数訪问到这个指针。pthread_exit运行完后不会返回到调用者,并且永远不会失败。
/* example.c*/
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#define err_sys(msg) \
do { perror(msg); exit(-1); } while(0)
#define err_exit(msg) \
do { fprintf(stderr, msg); exit(-1); } while(0)
void *thread_func(void *arg)
{
printf("hello world!\n");
sleep(1);
pthread_exit("jyh");
}
int main(void)
{
pthread_t tid;
char* p = NULL;
pthread_create(&tid, NULL, thread_func, NULL);
printf("pid: %lu\n", tid);
pthread_join(tid, (void **)&p);
printf("message: %s\n", p);
return 0;
}
用gcc编译函数:gcc example.c -lpthread -o example // -0后面是输出的文件名
编译好的文件前面直接加./去执行,结果如图:
image.png