Your first program
The smallest useful program creates a scheduler, runs one task on it and waits for the task to finish.
The task
A task is an object with a Run method. WaitableTask is a task that others
can wait for:
// A task is an object with a Run method. WaitableTask adds Wait, so others can wait
// for it.
class HelloTask : public TC::Tasks::WaitableTask
{
public:
void Run() noexcept override { std::printf("Hello from a task\n"); }
};Run is noexcept: a task reports problems through its own state, never by throwing.
The program
// The main thread becomes a task too, so it can wait without blocking a
// scheduler thread.
TC::ConvertThreadToTask();
// One scheduler thread per logical processor (numberOfThreads = 0).
TC::SchedulerInfo info{};
TC::ITaskScheduler* scheduler
= TC::CreateTaskScheduler(TC::SchedulerKind::Default, &info);
if (scheduler == nullptr)
return 1;
scheduler->Start();
HelloTask task; // must outlive the task: from AddTask until it has exited
scheduler->AddTask(&task);
task.Wait(); // suspends main until Run has returned
scheduler->Stop(); // only after every task has finished
scheduler->Destroy();
TC::ConvertTaskToThread();
return 0;Step by step:
- ConvertThreadToTask lets the main thread use the synchronization
primitives. Without it,
task.Wait()would not be allowed on this thread. See Threads as tasks. - CreateTaskScheduler creates a scheduler. A zero-initialized SchedulerInfo means one thread per logical processor and default queue sizes.
- Start starts the scheduler threads.
- AddTask queues the task. A scheduler thread picks it up and
calls
Run. - Wait suspends the main thread until the task has exited.
- Stop ends the scheduler threads, Destroy releases the scheduler, and ConvertTaskToThread undoes step 1.
Important
The task object must stay alive from AddTask until it has exited, and the scheduler must not be
stopped while tasks are still running or waiting. Here both are guaranteed because main waits
for the task before it stops the scheduler, and task lives until the end of main.
Output
Hello from a taskThe complete file is in the Hello task sample.
Next
- Debugging — Debug builds and the Visual Studio extension.
- The scheduler — what happens behind
AddTask. - Waiting for tasks — more than one task.