[英]Can I execute on get my `std::future` and wait on it too?
所以你可以創建一個std::future
,它在調用.get()
之前不起作用:
auto f_deferred = std::async( std::launch::deferred, []{ std::cout << "I ran\n"; } );
您還可以編寫一個可以等待的std::future
,並且可以通過任何線程中的代碼在任何時候做好准備:
std::packaged_task<void()> p( []( std::cout << "I also ran\n"; } );
auto f_waitable = p.get_future();
如果你調用f_deferred.wait_for(1ms)
,它就不會打擾等待了。 如果你調用f_deferred.get()
,你選擇的lambda(在這種情況下,打印"I ran\\n"
的lambda執行。
如果你調用f_waitable.get()
,管理任務的代碼就無法知道某人正在等待未來。 但是如果你調用f_deferred.wait(1ms);
,你只需立即獲得future_status::deferred
。
有什么方法可以把這兩個結合起來嗎?
具體的用例是當人們排隊任務時返回期貨的線程池。 如果一個未排隊的未來是.get()
'd,我想使用被阻塞的線程來執行任務而不是讓它空閑。 另一方面,我希望返回期貨的人能夠確定任務是否完成,甚至等待有限的時間來完成任務。 (在你等待的情況下,我等你的線程在你等待期間閑置了)
如果不這樣做,是否有解決方案可以解決這個問題,而不是讓我的線程池返回一個具有所有局限性的未來? 我聽說期貨沒有未來,問題期貨解決存在更好的解決方案。
我不確定這是否正是您所需要的,但它的目的是說明我在評論中建議的內容。 至少,我希望如果它不能滿足您的所有需求,它會為您提供一些實現所需內容的想法。
免責聲明:這非常粗糙。 很多事情當然可以更優雅,更有效地完成。
#include <iostream>
#include <thread>
#include <future>
#include <memory>
#include <functional>
#include <queue>
#include <random>
#include <chrono>
#include <mutex>
typedef std::packaged_task<void()> task;
typedef std::shared_ptr<task> task_ptr;
typedef std::lock_guard<std::mutex> glock;
typedef std::unique_lock<std::mutex> ulock;
typedef unsigned int uint;
typedef unsigned long ulong;
// For sync'd std::cout
std::mutex cout_mtx;
// For task scheduling
std::mutex task_mtx;
std::condition_variable task_cv;
// Prevents main() from exiting
// before the last worker exits
std::condition_variable kill_switch;
// RNG engine
std::mt19937_64 engine;
// Random sleep (in ms)
std::uniform_int_distribution<int> sleep(100, 10000);
// Task queue
std::queue<task_ptr> task_queue;
static uint tasks = 0;
static std::thread::id main_thread_id;
static uint workers = 0;
template<typename T>
class Task
{
// Not sure if this needs
// to be std::atomic.
// A simple bool might suffice.
std::atomic<bool> working;
task_ptr tp;
public:
Task(task_ptr _tp)
:
working(false),
tp(_tp)
{}
inline T get()
{
working.store(true);
(*tp)();
return tp->get_future().get();
}
inline bool is_working()
{
return working.load();
}
};
auto task_factory()
{
return std::make_shared<task>([&]
{
uint task_id(0);
{
glock lk(cout_mtx);
task_id = ++tasks;
if (std::this_thread::get_id() == main_thread_id)
{
std::cout << "Executing task " << task_id << " in main thread.\n";
}
else
{
std::cout << "Executing task " << task_id << " in worker " << std::this_thread::get_id() << ".\n";
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(sleep(engine)));
{
glock lk(cout_mtx);
std::cout << "\tTask " << task_id << " completed.\n";
}
});
}
auto func_factory()
{
return [&]
{
while(true)
{
ulock lk(task_mtx);
task_cv.wait(lk, [&]{ return !task_queue.empty(); });
Task<void> task(task_queue.front());
task_queue.pop();
// Check if the task has been assigned
if (!task.is_working())
{
// Sleep for a while and check again.
// If it is still not assigned after 1 s,
// start working on it.
// You can also place these checks
// directly in Task::get()
{
glock lk(cout_mtx);
std::cout << "\tTask not started, waiting 1 s...\n";
}
lk.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
lk.lock();
if (!task.is_working())
{
{
glock lk(cout_mtx);
std::cout << "\tTask not started after 1 s, commencing work...\n";
}
lk.unlock();
task.get();
lk.lock();
}
if (task_queue.empty())
{
break;
}
}
}
};
}
int main()
{
engine.seed(std::chrono::high_resolution_clock::now().time_since_epoch().count());
std::cout << "Main thread: " << std::this_thread::get_id() << "\n";
main_thread_id = std::this_thread::get_id();
for (int i = 0; i < 50; ++i)
{
task_queue.push(task_factory());
}
std::cout << "Tasks enqueued: " << task_queue.size() << "\n";
// Spawn 5 workers
for (int i = 0; i < 5; ++i)
{
std::thread([&]
{
{
ulock lk(task_mtx);
++workers;
task_cv.wait(lk);
{
glock lk(cout_mtx);
std::cout << "\tWorker started\n";
}
}
auto fn(func_factory());
fn();
ulock lk(task_mtx);
--workers;
if (workers == 0)
{
kill_switch.notify_all();
}
}).detach();
}
// Notify all workers to start processing the queue
task_cv.notify_all();
// This is the important bit:
// Tasks can be executed by the main thread
// as well as by the workers.
// In fact, any thread can grab a task from the queue,
// check if it is running and start working
// on it if it is not.
auto fn(func_factory());
fn();
ulock lk(task_mtx);
if (workers > 0)
{
kill_switch.wait(lk);
}
return 0;
}
這是我的CMakeLists.txt
cmake_minimum_required(VERSION 3.2)
project(tp_wait)
set(CMAKE_CXX_COMPILER "clang++")
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Build type" FORCE)
find_package(Threads REQUIRED)
add_executable(${PROJECT_NAME} "main.cpp")
target_link_libraries(${PROJECT_NAME} ${CMAKE_THREAD_LIBS_INIT})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.