我在网上搜索了所有答案,但没有找到任何解决方案。你能帮忙吗?我的问题是我试图将 Lambda 发送到另一个函数并使用Pthread库跨多个线程运行 lambda。接下来是代码:
  1    #include <iostream>
  2    #include <stdlib.h>
  3    #include <pthread.h>
  4    #include <vector>
  5 
  6    using namespace std;
  7 
  8 
  9   template<class InputIt, class Function>
 10    inline Function parallel_fun(InputIt first, InputIt last, Function f)
 11    {
 12         pthread_t threads[4];
 13 
 14       for (int i=0; first != last; ++first) {
 15 
 16          pthread_create(&threads[i], nullptr,f , nullptr);
 17 
 18           i++;
 19        }
 20 
 21      for (int i=0; i<4;i++) {
 22 
 23          pthread_join(threads[i],nullptr);
 24 
 25 
 26        }
 27 
 28 
 29 
 30 
 31    return f;
 32   }
 33 
 34 
 35    int main()
 36   {
 37    int z=90;
 38    vector<int> a(4);
 39     a[0]=1; a[1]=2;
 40     parallel_fun(a.begin(), a.end(), [=](void* data) -> void*
 41                     {
 42          cout<<"test"<<z<<endl;
 43            //do something
 44          });
 45 
 46 
 47 
 48 return 0;
 49 }
我使用以下行进行编译:g++ -std=c++0x -pthread test.cpp -o a
我收到这个错误:
test.cpp: In function ‘Function parallel_fun(InputIt, InputIt, Function) [with InputIt = __gnu_cxx::__normal_iterator<int*, std::vector<int> >, Function = main()::<lambda(void*)>]’:
test.cpp:44:11:   instantiated from here
test.cpp:16:10: error: cannot convert ‘main()::<lambda(void*)>’ to ‘void* (*)(void*)’ for argument ‘3’ to ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)’