Linux多线程编程学习代码(代码已上传gitee,还请各位兄弟点个Star哦!)
https://gitee.com/chenshao777/linux_thread.git
笔记:
线程链接 pthread_join
int pthread_join(pthread_t thread, void **retval);
功能:
1.调用该函数的线程会一直阻塞,直到指定pid为thread的线程调用pthread_exit、return或者被取消
2.pthread_join会使指定的线程处于分离状态,分离状态的线程不能被join
参数:
thread:链接线程的pid
retval:返回码
如果指定线程被取消,retval被置为PTHREAD_CANCELED
如果调用成功,函数返回0
失败返回错误码
spu.h文件
#ifndef _SPU_H_
#define _SPU_H_#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>#endif
04.thread_join.c文件
/*1.创建两个线程,其中线程2执行过程中自己分离自己2.main线程中join两个线程3.join线程1成功,返回码为0,pthread_join返回04.join线程2失败,返回码随机,pthread_join返回22,表示线程不可链接
*/#include "spu.h"void *thread_fun1(void *arg)
{for(int i = 0; i< 10; i++)printf("thread01 : %d\n", i);return (void*)0;
}void *thread_fun2(void *arg)
{for(int i = 100; i< 110; i++){printf("thread02 : %d\n", i);pthread_detach(pthread_self()); //分离线程,分离自己,参数:线程id}return (void*)0;
}int main(int argc, char *argv[])
{ int err1, err2;pthread_t thread_id1,thread_id2; void * __thread_return1, * __thread_return2;err1 = pthread_create(&thread_id1, NULL, thread_fun1, NULL);err2 = pthread_create(&thread_id2, NULL, thread_fun2, NULL);if(err1 || err2)printf("create failed!\n");elseprintf("create success!\n");printf("join thread01 return %d\n",pthread_join(thread_id1, &__thread_return1));printf("join thread02 return %d\n",pthread_join(thread_id2, &__thread_return2));printf("线程1返回码 %d\n",__thread_return1);printf("线程2返回码 %d\n",__thread_return2);return 0;
}