在C++中动态给出函数参数

Giving a function argument dynamically in C++

本文关键字:函数 参数 动态 C++      更新时间:2023-10-16

我有以下代码,我根据下面的 for 循环创建线程,pthread 中的第三个参数需要一个 void* (((void(,我给它一个字符串参数。问题是每个线程都有自己的方法,即线程 0 有它的方法 thread0((。我希望能够根据 for 循环的 t 设置方法而不会收到以下错误:

main2.cpp:40:51: error: cannot convert ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘void* (*)(void*)’ for argument ‘3’ to ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)’
 err = pthread_create(&threads[t], &attr,method, &t);
for(t = 0; t <5; t++){;
    printf("Creating thread %dn",t);
    std::string method = "thread"+t;
    err = pthread_create(&threads[t], &attr,method, &t);
    if(err != 0) exit(-1);
}

关于函数指针的错误消息非常清楚,您无法将 c++ 符号转换为字符串,反之亦然。

以下是文档中给出的pthread_create()签名:

概要

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

您可以执行以下操作:

typedef void* (*start_routine_t)(void*);
void* foo_0(void*) { return nullptr; }
void* foo_1(void*) { return nullptr; }    
void* foo_2(void*) { return nullptr; }
void* foo_3(void*) { return nullptr; }
void* foo_4(void*) { return nullptr; }
constexpr std::map<std::string,start_routine_t> thread_funcs {
    { "thread_0" , foo_0 } ,
    { "thread_1" , foo_1 } ,
    { "thread_2" , foo_2 } ,
    { "thread_3" , foo_3 } ,
    { "thread_4" , foo_4 } ,
};
pthread_t threads[5];

// ....
for(t = 0; t <5; t++){;
    printf("Creating thread %dn",t);
    std::ostringstream method;
    method << "thread_" <<t;
    err = pthread_create(&threads[t], &attr,method, &thread_funcs[method.str()],nullptr);
    if(err != 0) exit(-1);
}

或者更直接的方法根本不使用字符串:

start_routine_t thread_funcs[5] = { foo_0, foo_1, foo_2, foo_3, foo_4 }; 
pthread_t threads[5];
// ...
for(t = 0; t <5; t++){
    printf("Creating thread %dn",t);
    err = pthread_create(&threads[t], &attr,method, thread_funcs[t], nullptr);
    if(err != 0) exit(-1);
}

正如您还要求 c++-11 设施:

  1. 直接使用 std::thread 而不是 pthread-API。如果目标环境正确支持 pthreads,则通常可以使用 ABI std::thread
  2. 使用 lambda 函数动态引用特定例程:

    std::vector<std::thread> threads(5);
    for(t = 0; t <5; t++){
       printf("Creating thread %dn",t);
       auto thread_func = [t]() {
           switch(t) {
           case 0: foo_0(); break;
           case 1: foo_1(); break;
           case 2: foo_2(); break;
           case 3: foo_3(); break;
           case 4: foo_4(); break;
           }               
       };
       threads[t] = std::thread(thread_func);
    }
    

    上面的代码示例可能不是最好的(最有效的(,但演示了如何动态映射函数调用。