void *(*start_routine) (void *)的理解

这里*start_routine是定义的函数指针 ,这个函数的返回值是void *,参数是void *

形如pthread_create函数的函数格式

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg)

这里第三个参数是要传入一个函数地址,这个函数定义格式如下:

void *start_routine(void *args)

{//

return (void*)111;

}

有些地方会遇见

typedef void *(*start_routine) (void *)

这里表示定义了一个函数指针start_routine,返回类型为void*,参数为void*。

当我们想构建一个函数集的时候就可以用这个方法:

#include <iostream>
#include <function>
#include <vector>
using namespace std;

vector<function<void()>> funcs;
//typedef vector<function<void()>> funcs;
//定义一个funcs的函数集合 

void show()
{
cout<<"hello world"<<endl;
}
void print()
{
cout<<"hello print"<<endl;
}


int main()
{
funcs.push_back(show);
funcs.push_back(print);
funcs.push_back([]()
{
cout<<"你好"<<endl;
})
//调用
for(auto &f:funcs)
{
f();
}
return 0;
}

关于传地址问题,这里比如:

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

什么时候加&符号就取决于你传入的类型需要什么,比如这里pthread_join函数第二个是void **retval类型,我们建一个:

void *ret=nullptr;

则需要加入取地址符号:

pthread_join(tid,&ret);

像上面的pthread_creat函数,我们建一个:

(注:在C语言中,函数名就是函数地址,&函数名也是函数地址,调用函数用函数名就可以。)

void *startRoutine(void *args)
{
//
return (void*)111;
}

此时传入函数名地址就行,如:

pthread_t tid;

int n=pthread_create(&tid,nullptr,startRoutine,(void*)"thread1");

如下情况不需要传入&:

static void printTid(const char*name,const pthread_t &tid)
{
        printf("%s 正在运行,thread id:0x%x,global_value:%d\n",name,tid,global_value);
}
const char *name=static_cast<const char*>(args);

printfTid(name,pthread_self());

这里name是一个char*类型的指针变量,自身就是地址。

保证传入的地址与指针层数对应即正确。

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值