我有一个main.cpp文件,其中有以下代码
paral(start, end, [&](int i){
C1[i] = A1[i] + B[i];
}, numThreads);`
我在otherfile.cpp中有paral
定义,其中有以下代码
void paral(int start, int end, T &&lambda, int nT){
pthread_t thread1;
int status = pthread_create(&thread1, NULL,lambda ,1);//Should execute lambda(1)
lambda(2);//Executed by main thread
//Code for join and so on
}
它说:
无法将lambda转换为(void *)(*)(void *)。
我试图强制转换lambda函数并将其传递给pthread,但这没有帮助。 我也想从无法创建的线程中调用lambda函数。
答案 0 :(得分:1)
您应该将lambda转换为std :: function。以下代码演示了该方法。我没有安装pthreads。所以我改用_beginthread
函数,这很相似。
#include <process.h>
#include <Windows.h>
#include <iostream>
#include <functional>
using thread_start = std::function<void ()>;
void function_executor( void* arg ) {
// Convert void* to std::function back and execute it
auto ts = reinterpret_cast<thread_start*>( arg );
(*ts)();
}
template<typename Handler>
void paral(int start, int end, Handler &&handler, int nT){
for( ; start < end; ++start ) {
// Create instance of thread_start (capture argument)
thread_start func = std::function( [&, i = start] { handler(i); } );
// ... and pass all this to the newly created thread
auto cpp_handle = _beginthread( function_executor, 0, &func );
// Wait for thread complete
if( -1 != cpp_handle ) {
auto win_handle = reinterpret_cast<HANDLE>( cpp_handle );
WaitForSingleObject( win_handle, INFINITE );
}
}
}
int main() {
int C1[10], A1[10], B[10];
paral(0, 10, [&](int i){ C1[i] = A1[i] + B[i]; }, 1);
std::cout << "Done. Bye!" << std::endl;
}