C++ 将Lambda传递给pthread_create?
我在网上搜索答案,但没有找到任何解决办法。你能帮忙吗。 我的问题是,我试图将Lambda发送到另一个函数,并使用C++ 将Lambda传递给pthread_create?,c++,c++11,C++,C++11,我在网上搜索答案,但没有找到任何解决办法。你能帮忙吗。 我的问题是,我试图将Lambda发送到另一个函数,并使用Pthread库跨多个线程运行Lambda。接下来是代码: 1 #include <iostream> 2 #include <stdlib.h> 3 #include <pthread.h> 4 #include <vector> 5 6 using namespace std;
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 }
除非lambda没有捕获,否则不会将lambda转换为函数指针。(§5.1.2p6)。因此,如果您需要捕获
z
,那么您就不走运了
C接口希望您对闭包使用void*
参数。你可以这样做,这将是丑陋的(但类似于C),或者你可以使用新的C++ 11线程支持库,如果你的C++环境支持它。
我对新的C++11API没有把握。我想我的钱不够
是时候学习新的API了
今天是你的幸运日。C++11api受到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
});
}
#包括
#包括
#包括
#包括
模板
内联
作用
并行功能(先输入,后输入,函数f)
{
标准:螺纹[4];
for(int i=0;first!=last;++first)
{
线程[i]=std::thread(f);
i++;
}
对于(In i=0;II怀疑你必须切换到C++ 11多线程支持,或者放弃lambda。我不知道如何实现lambda,但是如果它们可以直接传递到C API,我需要惊讶的是,需要捕获局部变量,然后使用lambda。我注意到,如果我从代码中删除Z,程序就不会出错。或者。无论如何,谢谢你的帮助。我不确定新的C++11 API。我认为我没有足够的时间来学习新的API。考虑到你了解POSIX线程,学习C++11线程支持一开始并不那么复杂。这不是问题的答案。也许OP对这个备选方案感到满意“当然不是每个人都来问这个问题寻求答案。@Howard Hinnant,如果我们将std::vector a(4)
更改为std::vector a(10),您的代码会如何运行?”
?这是OP代码的忠实翻译,不多也不少。OP代码中的任何错误也被翻译成C++11。如果我的lambda函数接受一个参数,比如[=](int x){…},我将如何使用线程调用?std::thread(f)?。
#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
});
}