主线程将x传递给子线程,子线程将结果x再传递给主线程。
#include <iostream>
#include <future>
#include <thread>
using namespace std;
void myfun(int N,int& x)
{
int res =1;
for(int i=N;i>1;i--)
{
res *= i;
}
cout<<"Result res is:"<<res<<endl;
x=res;
}
int main() {
int x;
std::thread t1(myfun,4,std::ref(x));
t1.join();
cout<<"Result x is:"<<x<<endl;
return 0;
}
现在x是主线程与子线程的共有资源,因此我们需要来进行保护
#include <iostream>
#include <future>
#include <thread>
using namespace std;
mutex mu;
condition_variable cond;
void myfun(int N,int& x)
{
int res =1;
for(int i=N;i>1;i--)
{
res *= i;
}
cout<<"Result res is:"<<res<<endl;
x=res;
}
int main() {
int x;
std::thread t1(myfun,4,std::ref(x));
t1.join();
cout<<"Result x is:"<<x<<endl;
return 0;
}
这样就需要调用mu.lock()/mu.unlock() cond.wait()/cond.notify()非常的麻烦。同时还有两个全局变量需要注意。这样我们的代码结构就会变得混乱。
#include <iostream>
#include <thread>
#include <vector>
#include <future>
using namespace std;
int fun1(std::future<int>& f)
{
int res =1;
int N = f.get();
for(int i=N;i>1;i--)
{
res *= i;
}
cout<<"Result res is:"<<res<<endl;
return res;
}
int main()
{
int x;
std::promise<int> p;
std::future<int> f =p.get_future();
// future<int> fu = async(fun1,4);
future<int> fu = async(std::launch::async,fun1,std::ref(f));
//std::launch::defered,fun1 will be executed in the same thread
//std::launch::async,fun1 will be executed in another thread
//std::launch::defered|std::launch::async fun1 will be executed depend on the
//do some thing
std::this_thread::sleep_for(chrono::milliseconds(20));
p.set_value(4);
x = fu.get();
//fu.get();//get only can be called once,or it will be crash
cout << "Get from child:"<<x<<endl;
return 0;
}
如果把p.set_value(4);去除会报一个std::future_errc::broken_promise的错误。
使用set_exception()就可以打破这个promise。会返回To err is human 这个错误。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)