标签:用法 对象 name ima 构造 pre typename cout alt
std::packaged_task<double(int)> task(func);//func是个方法,有一个参数,类型是int,返回值类型是double
std::packaged_task<std::string(int)> task1(call_texi);
std::future<std::string> ft1 = task1.get_future();
task1(100);//task1执行完成后,才能执行下面的打印输出的代码,不是在新的线程里执行task1(100)
std::cout << "111111111111111111111111111111" << std::endl;
std::packaged_task<std::string(int)> task1(call_texi);
std::future<std::string> ft1 = task1.get_future();
std::thread t1(std::move(task1), 100);
t1.detach();//task1(100)是异步执行,也就是在新的线程里执行。
std::cout << "111111111111111111111111111111" << std::endl;
#include <deque>
#include <mutex>
#include <future>
#include <thread>
#include <iostream>
#include <unistd.h>
#include <string>
//#include <utility>
std::mutex mut;
std::deque<std::packaged_task<std::string(int)>> tasks;
void manage_tasks(){
while(true){
sleep(1);
//std::cout << "please wait for a moument" << std::endl;
std::packaged_task<std::string(int)> task;
{
std::lock_guard<std::mutex> lg(mut);
if(tasks.empty()) continue;
std::cout << "----------------------not empty---------------" << std::endl;
task = std::move(tasks.front());
tasks.pop_front();
}
task(1);
//std::string s = task(10);
}
}
template<typename Call>
std::future<std::string> add_task(Call ca){
std::cout << "----------------------add_task---------------" << std::endl;
std::packaged_task<std::string(int)> task(ca);
std::future<std::string> ret = task.get_future();
std::lock_guard<std::mutex> lg(mut);
tasks.push_back(std::move(task));
return ret;
}
std::string call_texi(int i = 0){
std::cout << "-------------jiaoche---------------" << std::endl;
if(i == 1){
return "aaa";
}else{
return "bbb";
}
}
std::string call_zhuanche(int i){
std::cout << "zhuanche:" << i << std::endl;
return std::to_string(i);
}
int main(){
std::thread background_thread(manage_tasks);
background_thread.detach();
std::future<std::string> fut1 = add_task(call_texi);
std::cout << fut1.get() << std::endl;
std::future<std::string> fut2 = add_task(call_zhuanche);
std::cout << fut2.get() << std::endl;
pthread_exit(NULL);
}
编译方法:
g++ -g XXX.cpp -std=c++11 -pthread
运行结果:
----------------------add_task---------------
----------------------not empty---------------
-------------jiaoche---------------
aaa
----------------------add_task---------------
----------------------not empty---------------
zhuanche:1
1
c/c++ 多线程 等待一次性事件 packaged_task用法
标签:用法 对象 name ima 构造 pre typename cout alt
原文地址:https://www.cnblogs.com/xiaoshiwang/p/10014219.html