如何理解pthread_join

可以理解为wait()/waitpid()

区别是wait是的等待子进程退出
只要子进程退出,父进程就立即接着执行

pthread_join是等待线程退出
线程退出接着执行。

在这里插入图片描述
想做什么就去做,你所经历的,都将成为经验,但纠结只会浪费时间
——亲爱的客栈

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
pthread_create()和pthread_join()是Linux系统中用于创建和等待线程的函数。 pthread_create()函数用于创建一个新的线程,其原型如下: ```c int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg); ``` 其中,thread参数是指向线程标识符的指针,attr参数是指向线程属性的指针,start_routine参数是指向线程函数的指针,arg参数是传递给线程函数的参数。 pthread_join()函数用于等待一个线程的结束,其原型如下: ```c int pthread_join(pthread_t thread, void **retval); ``` 其中,thread参数是要等待的线程标识符,retval参数是指向线程返回值的指针。 下面是一个简单的例子,演示了如何使用pthread_create()和pthread_join()函数创建和等待线程: ```c #include <stdio.h> #include <stdlib.h> #include <pthread.h> void *print_message_function(void *ptr); int main() { pthread_t thread1, thread2; char *message1 = "Thread 1"; char *message2 = "Thread 2"; int ret1, ret2; // 创建线程1 ret1 = pthread_create(&thread1, NULL, print_message_function, (void *)message1); if (ret1) { printf("Error: pthread_create() failed\n"); exit(EXIT_FAILURE); } // 创建线程2 ret2 = pthread_create(&thread2, NULL, print_message_function, (void *)message2); if (ret2) { printf("Error: pthread_create() failed\n"); exit(EXIT_FAILURE); } // 等待线程1结束 ret1 = pthread_join(thread1, NULL); if (ret1) { printf("Error: pthread_join() failed\n"); exit(EXIT_FAILURE); } // 等待线程2结束 ret2 = pthread_join(thread2, NULL); if (ret2) { printf("Error: pthread_join() failed\n"); exit(EXIT_FAILURE); } printf("Main thread exiting\n"); exit(EXIT_SUCCESS); } void *print_message_function(void *ptr) { char *message; message = (char *)ptr; printf("%s\n", message); pthread_exit(NULL); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

公孙无语

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值