多线程--pthread_join函数详解

本文介绍Linux环境下多线程编程的基础知识,包括线程的创建、等待和退出等核心函数的使用方法,并通过示例代码展示了互斥锁的作用及线程间的同步机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

From

http://xsh8637.blog.163.com/blog/static/24099666200910942025662/?fromdm&fromSearch&isFromSearchEngine=yes

 

单处理器上的linux多线程,是通过分时操作完成的;

此时互斥锁的作用,只有在时间足够的情况下才能体现出来,即有时线程内需要延时;

否则只有第一个线程不断解锁和获锁,别的线程在第一个线程执行完前无法获得互斥锁。

函数pthread_join用来等待一个线程的结束。函数原型为:

  extern int pthread_join __P ((pthread_t __th, void **__thread_return));

  第一个参数为被等待的线程标识符,第二个参数为一个用户定义的指针,它可以用来存储被等待线程的返回值。这个函数是一个线程阻塞的函数,调用它的函数将一直等待到被等待的线程结束为止,当函数返回时,被等待线程的资源被收回。一个线程的结束有两种途径,一种是象我们上面的例子一样,函数结束了,调用它的线程也就结束了;另一种方式是通过函数pthread_exit来实现。它的函数原型为:

  extern void pthread_exit __P ((void *__retval)) __attribute__ ((__noreturn__));

  唯一的参数是函数的返回代码,只要pthread_join中的第二个参数thread_return不是NULL,这个值将被传递给 thread_return。最后要说明的是,一个线程不能被多个线程等待,否则第一个接收到信号的线程成功返回,其余调用pthread_join的线程则返回错误代码ESRCH。

  在这一节里,我们编写了一个最简单的线程,并掌握了最常用的三个函数pthread_create,pthread_join和pthread_exit。下面,我们来了解线程的一些常用属性以及如何设置这些属性。

多线程--pthread_join函数详解 - xsh8637 - 第七天堂

///////////////////////////////////////////////////////////////////////////

源程序:

/*thread_example.c :  c multiple thread programming in linux

   */

#include

#include

#include

#include

#define MAX1 10

#define MAX2 30

pthread_t thread[2];

pthread_mutex_t mut;

int number=0, i;

void *thread1()

{

        printf ("thread1 : I'm thread 1/n");

        for (i = 0; i < MAX1; i++)

        {

                printf("thread1 : number = %d  i=%d/n",number,i);

                pthread_mutex_lock(&mut);

                        number++;

                pthread_mutex_unlock(&mut);

                sleep(2);

        }

        printf("thread1 :Is main function waiting for me acomplishing task? /n");

        pthread_exit(NULL);

}

void *thread2()

{

        printf("thread2 : I'm thread 2/n");

        for (i = 0; i < MAX2; i++)

        {

                printf("thread2 : number = %d  i=%d/n",number,i);

                pthread_mutex_lock(&mut);

                        number++;

                pthread_mutex_unlock(&mut);

                sleep(3);

        }

        printf("thread2 :Is main function waiting for me  to acomplish task ?/n");

        pthread_exit(NULL);

}

void thread_create(void)

{

        int temp;

        memset(&thread, 0, sizeof(thread));          //comment1

        /*创建线程*/

        if((temp = pthread_create(&thread[0], NULL, thread1, NULL)) != 0)       //comment2

                printf("线程1创建失败!/n");

        else

                printf("Thread 1 is established/n");

        if((temp = pthread_create(&thread[1], NULL, thread2, NULL)) != 0)  //comment3

                printf("线程2创建失败");

        else

                printf("Thread 2 is established/n");

}

void thread_wait(void)

{

        /*等待线程结束*/

        if(thread[0] !=0) {                   //comment4

                pthread_join(thread[0],NULL);

                printf("Thread 1 is over /n");

        }

        if(thread[1] !=0) {                //comment5

                pthread_join(thread[1],NULL);

                printf("Thread 2 is over/n");

        }

}

int main()

{

        /*用默认属性初始化互斥锁*/

        pthread_mutex_init(&mut,NULL);

        printf("I am the main funtion,and I am establishing threads. Ha-ha/n");

        thread_create();

        printf("I am the main funtion,and I am waiting for thread to accomplish task. Ha-ha/n");

        thread_wait();

        return 0;

}

///////////////////////////////////////////////////////////

执行情况1(linux终端):[root@localhost root]# gcc -o joint joint.c -lpthread

[root@localhost root]# ./joint

I am the main funtion,and I am establishing threads. Ha-ha

thread1 : I'm thread 1

thread1 : number = 0  i=0

Thread 1 is established

thread2 : I'm thread 2

thread2 : number = 1  i=0

Thread 2 is established

I am the main funtion,and I am waiting for thread to accomplish task. Ha-ha

thread1 : number = 2  i=1

thread2 : number = 3  i=2

thread1 : number = 4  i=3

thread2 : number = 5  i=4

thread1 : number = 6  i=5

thread1 : number = 7  i=6

thread2 : number = 8  i=7

thread1 : number = 9  i=8

thread2 : number = 10  i=9

thread1 :Is main function waiting for me acomplishing task?

Thread 1 is over

thread2 : number = 11  i=11

thread2 : number = 12  i=12

thread2 : number = 13  i=13

thread2 : number = 14  i=14

thread2 : number = 15  i=15

thread2 : number = 16  i=16

thread2 : number = 17  i=17

thread2 : number = 18  i=18

thread2 : number = 19  i=19

thread2 : number = 20  i=20

thread2 : number = 21  i=21

thread2 : number = 22  i=22

thread2 : number = 23  i=23

thread2 : number = 24  i=24

thread2 : number = 25  i=25

thread2 : number = 26  i=26

thread2 : number = 27  i=27

thread2 : number = 28  i=28

thread2 : number = 29  i=29

thread2 :Is main function waiting for me  to acomplish task ?

Thread 2 is over

### pthread_join 函数详解 `pthread_join` 是 POSIX 线程库中的一个重要函数,用于等待某个线程完成并回收其资源。它的主要作用是让主线程或其他线程能够同步地等待目标线程结束运行。 #### 函数原型 以下是 `pthread_join` 的标准定义: ```c #include <pthread.h> int pthread_join(pthread_t thread, void **retval); ``` - 参数说明: - `thread`: 要等待的目标线程 ID。 - `retval`: 如果不为空,则存储目标线程退出时返回的值(通常是一个指针)。如果不需要获取返回值,可以传入 `NULL`[^3]。 - 返回值: - 成功时返回 0。 - 失败时返回错误码。 #### 工作原理 当调用 `pthread_join` 时,当前线程会阻塞直到指定的线程 `thread` 完成为止。一旦目标线程结束,`pthread_join` 将解除阻塞状态,并可以选择接收该线程的返回值。此外,`pthread_join` 还负责清理与目标线程关联的系统资源,防止内存泄漏。 #### 示例代码 下面展示如何使用 `pthread_join` 来等待子线程完成: ```c #include <pthread.h> #include <stdio.h> #include <stdlib.h> // 子线程执行的任务 void* task_function(void* arg) { int id = *((int*)arg); printf("Thread %d is running.\n", id); sleep(2); // 模拟耗时操作 printf("Thread %d has finished its work.\n", id); free(arg); // 释放传递给线程的参数 pthread_exit((void*)id); // 返回线程ID作为结果 } int main() { pthread_t threads[5]; int i; // 创建多个线程 for (i = 0; i < 5; ++i) { int* p = malloc(sizeof(int)); *p = i; if (pthread_create(&threads[i], NULL, task_function, p)) { fprintf(stderr, "Error creating thread %d\n", i); exit(EXIT_FAILURE); } } // 等待所有线程完成 void* status; for (i = 0; i < 5; ++i) { if (pthread_join(threads[i], &status)) { fprintf(stderr, "Error joining thread %d\n", i); continue; } printf("Thread %ld returned with value %ld\n", threads[i], (long)status); } return EXIT_SUCCESS; } ``` 上述代码展示了以下几个要点: 1. 主线程创建了五个子线程,每个子线程都执行自己的任务。 2. 使用 `pthread_join` 让主线程依次等待这些子线程完成。 3. 获取并打印每个子线程的返回值。 #### 注意事项 - 如果未调用 `pthread_join` 或者显式调用了 `pthread_detach`,则无法再对该线程的状态进行查询或回收资源。 - 同一线程不能被多次加入 (`join`),否则会产生未定义行为。 - 当前线程试图对自己调用 `pthread_join` 也会引发死锁情况。 #### 清理机制补充 为了处理可能发生的异常终止场景,在某些情况下还可以结合 `pthread_cleanup_push/pop` 对来设置清理回调函数[^4]。这有助于在线程提前退出或者被取消的情况下安全释放资源。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值