主要了解这三个函数
/*pthread_create函数主要完成线程的创建. 参数解释: thread参数是一个线程标识符,当新创建一个线程的时候,会以此变量记录线程标识符 attr参数用于设置线程的属性,一般使用时,常为NULL start_routine 函数指针,指向一个函数.也就是这个线程所要运行的函数 arg参数:线程所指向的函数的参数,如果函数不需要参数,设为NULL */ int pthread_create(pthread_t *thread,pthread_attr_t *attr, void *(*start_routine)(void *),void *arg); /* pthread_join : 调用pthread_join的线程将等待参数thread所指向的线程 结束为止,当pthread_join函数返回时,被等待线程的资源被收回。 参数解释: 第一个参数为被等待的线程标识符, 第二个参数为一个用户定义的指针,它可以用来存储被等待线程的返回值 */ int pthread_join(pthread *thread,void **thread_return); /* pthread_exit 主要用于结束线程. 下面主要解释一下pthread_exit的参数 retval .当线程调用pthread_exit时, 线程将退出,retval中保存需要返回的信息.只要pthread_join中的第二个参数thread_return不是NULL,这个值将被传递给thread_return. */ void pthread_exit(void *retval);
下面分析一个实例:
#include <pthread .h> #include <stdio .h> #include <errno .h> #include <string .h> void *thread_function(void *arg); char message[] = "Hello World"; int main() { int res; pthread_t a_thread; void *thread_result; res = pthread_create(&a_thread, NULL, thread_function, (void *)message); if (res != 0) { perror("Thread creation failed"); exit(1); } printf("Waiting for thread to finish...\n"); res = pthread_join(a_thread, &thread_result); //pthread_join 阻塞执行的线程直到某线程结束 if (res != 0) { perror("Thread join failed"); exit(1); } printf("Thread joined, it returned %s\n", (char *)thread_result); printf("Message is now %s\n", message); exit(0); } void *thread_function(void *arg) { printf("thread_function is running. Argument was %s\n", (char *)arg); sleep(3); strcpy(message, "Bye!"); pthread_exit("Thank you for the CPU time"); } </string></errno></stdio></pthread>
当主线程执行到pthread_create时,将创建一个新线程.我们将它称之为子线程
这时将根据cpu将主线程和子线程之间调度
当主线程执行到pthread_join的时候,将阻塞主线程的执行,直到a_thread所标示的子线程执行结束后,再执行主线程

执行结果
