将Lambda传递给pthread_create
passing Lambda to pthread_create?
我在所有的网上搜索答案,但没有找到任何解决方案。你能帮忙吗。我的问题是,我试图将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*)’
我不确定新的C++11 API。我觉得我不够是时候学习新的API了。
今天是你的幸运日。C++11 API受到pthreads的强烈影响。几乎是机械翻译。这是您在C++11中的代码转换:
#include <iostream>
#include <stdlib.h>
#include <thread>
#include <vector>
template<class InputIt, class Function>
inline
Function
parallel_fun(InputIt first, InputIt last, Function f)
{
std::thread threads[4];
for (int i=0; first != last; ++first)
{
threads[i] = std::thread(f);
i++;
}
for (int i=0; i<4;i++)
{
threads[i].join();
}
return f;
}
int main()
{
int z=90;
std::vector<int> a(4);
a[0]=1; a[1]=2;
parallel_fun(a.begin(), a.end(), [=]()
{
std::cout<<"test" << z << std::endl;
//do something
});
}
您的另一种选择是,弄清楚std::thread
是如何在pthreads之上实现的,相信我,这比上面显示的C++11翻译要复杂得多。
除非lambda没有捕获,否则不会从lambda转换为函数指针。(§5.1.2p6)。因此,如果你需要捕获z
,那你就运气不好了。
C接口希望您对闭包使用void*
参数。你可以这样做,这将是丑陋的(但类似C),或者你可以使用新的C++11线程支持库,如果你的C++环境支持的话
相关文章:
- Using C++ CryptAPI:CNG Create CSR
- 错误:(-210:不支持的格式或格式组合)功能'create'中的硬件视频解码器不支持视频源
- 在 c++11 中为 pthread 设置调度参数
- 如果不包含 pthread,为什么 GCC 的线程标准库实现会抛出异常?
- pthread只有在线程数量较少时才可以正常工作
- Firebase C++VS2018 SDL2-在Firebase::app::create(..)上执行异常处理
- pthread执行时间比顺序执行时间差
- 使用 -pthread 如何不违反 ODR 规则?
- 使用 pthread 的多线程
- QThread::create 似乎没有将参数传递给函数
- 销毁 pthread 互斥体和 C++ 中的取消初始化顺序
- 函数 AfxEndThread 中的读取访问冲突"pThread-> was nullptr"
- 锁定步进pthread互斥
- Pthread段错误,使用指向main中变量的指针
- pthread导致的内存泄漏
- GCC:--静态链接到pthread的整个存档配方在最近的GCC版本中停止工作
- 正确地编写一个类,并将pthread与vlc库和c++一起使用
- 为什么"non-standard syntax; use '&' to create a pointer to member"在 CTOR 中使用线程?
- QThread::create running on UI Thread
- 使用pthread Create创建两个类,并在cpp中相互访问