linux pthread_join使用

这个函数没有什么好说的。其实就两个参数,第一个是线程变量,第二个是线程返回值。其函数原型为:

int pthread_join(pthread_t thread,void** result);

不过查阅许多网上资料,依旧没有使用result这个形参的。一般的使用为pthread_join(thread,NULL);于是自己在想那个NULL能做啥米用。于是写下下面的代码:

#include <stdio.h> #include <pthread.h> int count =0; // 初始化mutex变量。 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void * print_count(int); int main() { const int num = 10; pthread_t threads[num]; int i=0; for(i=0; i< num; i++){ //第一个参数是pthread_t变量,第二个是pthread_t变量的属性 //第三个是pthread_t需要执行的函数,其函数原型为 // void* (*startfun)(void*) // 所以传入的是一个返回void*的函数(这里当然可以转换) // 并且接受的是void*的参数,所以需要把i转换为void * pthread_create(&threads[i],NULL,print_count,(void*)i); } void* result = NULL; for(i=0; i < num; i++){ // 这里就是同步得到结果。打印的是线程执行的状态,0为成功。非0失败 printf("end %d;\n",pthread_join(threads[i],&result)); if(result == NULL){ printf("NULL\n"); } else{ // 这里打印的是pthread_t执行完print_count后返回的结果。 printf("%x\n",result); } } return 0; } //这里返回的类型是void*,因为pthread_create中的函数指针为void* //这里的参数int i,可有可无,如果没有pthread_create中就使用NULL作为参数。 void * print_count(int i){ // 设置mutex锁 pthread_mutex_lock(&mutex); printf("thread: %d---> count %d\n",i,count); count++; sleep(2); printf("thread: %d---> count %d\n",i,count); // 释放锁 pthread_mutex_unlock(&mutex); //这里是返回值, void * result就可以被赋值了..否则为result = NULL return (void*)count; }

另外值得注意的是pthread_join()中第二个参数不要乱传。如果非NULL,可能造成segment failure.

另外这里如果使用c++进行编译可能会有void* (*)(int)不能转换为void*(*)(void*)的问题。这是因为c++编译器要求太严格了。只好改动函数签名为void * print_count(void *);之后再进行转换。现在终于知道为啥这么多人都喜欢在linux下使用c了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值