线程练习题

编写一个程序,主线程中创建一个子线程,容纳后让主线程先退出并返回一个值,子线程接合主线程后输出主线程的退出值,然后子线程退出.

/*******************************************************************
 *
 *	file name:  pthread.c
 *	author	 :  Dazz
 *	date	 :  2024/05/29
 *	function :  练习:编写一个程序,主线程中创建一个子线程,容纳后让主线程
 *              先退出并返回一个值,子线程接合主线程后输出主线程的退出值,
 *              然后子线程退出.
 *
 * 	note	 :  link with -pthread.
 *
 *	CopyRight (c)  2024  Dazz_24@163.com   All Right Reseverd
 *
 * *****************************************************************/

#include <stdio.h>
#include <pthread.h>

// 用于记录主线程的id
pthread_t thread_main;

// 子线程
void *
func(void *)
{
    // 定义一个变量来接收主线程的返回值
    int *resv;

    /*接收主进程的返回值:int pthread_join(pthread_t thread, void **retval);
    注意pthread_join会阻塞*/
    pthread_join(thread_main, (void **)&resv);

    // 输出主线程的返回值
    printf("this is the pthread of main return :%d\n", *resv);

    // 结束子线程
    pthread_exit(NULL);
}

int main()
{
    // 记录主线程的id
    thread_main = pthread_self();

    // 创建子线程
    pthread_t thread_p;
    pthread_create(&thread_p, NULL, func, NULL);

    // 定义一个变量用于返回的值
    int retval = 77777;

    // 结束主线程,并返回一个值void pthread_exit(void *retval);
    pthread_exit((void *)&retval);

    return 0;
}
posted @ 2024-05-29 15:20  Dazz_24  阅读(39)  评论(0)    收藏  举报