Skip to content

Instantly share code, notes, and snippets.

@tiandiao123
Created December 21, 2022 20:59
Show Gist options
  • Select an option

  • Save tiandiao123/083d43f321aadaa644fcca52f5666ef9 to your computer and use it in GitHub Desktop.

Select an option

Save tiandiao123/083d43f321aadaa644fcca52f5666ef9 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <thread>
#include <future>
#include <deque>
using namespace std;
std::deque<std::packaged_task<int()>> task_q;
std::mutex mu;
std::condition_variable cond;
int factorial(int N) {
int res = 1;
for(int i=N;i>1;i--){
res *= i;
}
cout <<"The result is : " << res << endl;
return res;
}
void thread_1(){
std::packaged_task<int()> t;
{
std::unique_lock<std::mutex> locker(mu);
cond.wait(locker, [](){
return !task_q.empty();
});
t = std::move(task_q.front());
task_q.pop_front();
}
t();
}
int main(){
std::thread t1(thread_1);
std::packaged_task<int()> t(std::bind(factorial, 6));
std::future<int> fu = t.get_future();
{
std::lock_guard<std::mutex> locker(mu);
task_q.push_back(std::move(t));
}
cond.notify_one();
cout << fu.get();
t1.join();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment