← 返回 citadel 的题目列表Implement a C++ Task Scheduler with Parameterized Tasks
类型:online_judge
Problem: Implement a C++ Task Scheduler with Parameterized Tasks
Implement a thread-safe C++ TaskScheduler. Callers can submit an arbitrary callable together with its arguments, and background worker threads execute the task asynchronously.
Requirements
Provide an interface similar to:
template <class F, class... Args>
auto submit(F&& f, Args&&... args)
-> std::future<std::invoke_result_t<F, Args...>>;
When submit is called:
Package f and args... as one task.
Put the task into a shared task queue.
An available worker eventually executes it.
Return a std::future that yields the result or rethrows an exception from task execution.
The scheduler receives the worker count at construction time.
Multiple caller threads may submit work concurrently.
Workers must block rather than busy-spin when the queue is empty.
Implement shutdown(): reject new submissions, drain all previously accepted work, then join worker threads.
Discuss destructor behavior, exception safety, void-returning tasks, and races between shutdown() and concurrent submit() calls.
Example
TaskScheduler scheduler(2);
auto f1 = scheduler.submit([](int a, int b) { return a + b; }, 3, 4);
auto f2 = scheduler.submit([] { /* side effect */ });
assert(f1.get() == 7);
f2.get();
scheduler.shutdown();
Target Complexity
O(1) additional overhead per submission, excluding task execution.
O(1) scheduling overhead to dequeue and run a task.