[Linux multithreaded programming - self-study record] 04. Thread link - pthread_join

Linux multi-threaded programming learning code (the code has been uploaded to gitee, please click Star!)

https://gitee.com/chenshao777/linux_thread.git


Notes:
thread link pthread_join
int pthread_join(pthread_t thread, void **retval);

Function:
1. The thread calling this function will be blocked until the thread with the specified pid as thread calls pthread_exit, return or is cancelled. 2.
pthread_join will make the specified thread in the separated state, and the thread in the separated state cannot be joined

Parameters:
thread: the pid of the linked thread
retval: the return code

If the specified thread is canceled, retval is set to PTHREAD_CANCELED

If the call is successful, the function returns 0
and returns an error code on failure


spu.h file

#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 file

/*
  1.创建两个线程,其中线程2执行过程中自己分离自己
  2.main线程中join两个线程
  3.join线程1成功,返回码为0,pthread_join返回0
  4.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");
	else
		printf("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;
}

Guess you like

Origin blog.csdn.net/HuangChen666/article/details/130454704