Hello task
The smallest complete program: it creates a scheduler, runs one task on it, waits for the task from
main and shuts everything down in the right order. Every other sample follows the same frame.
Your first program walks through it step by step.
// Hello task: start a scheduler, run one task on it, wait for the task, shut down.
#include <Windows.h>
#include <cstdio>
#include <ThinkMeta.ConcurrentTasks/Core.h>
import ThinkMeta.ConcurrentTasks.Tasks.WaitableTask;
namespace TC = ThinkMeta::ConcurrentTasks;
// 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"); }
};
int main()
{
// 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;
}Build and run
A console program. With the core's props file imported and the library referenced (see Set up a project) it needs nothing else. It prints:
Hello from a taskWhat to notice
mainbecomes a task. ConvertThreadToTask lets the main thread call Wait; without it, waiting is not allowed on a plain OS thread. ConvertTaskToThread undoes it at the end.- The order of the shutdown. Stop only after every task has finished – here guaranteed by the wait – then Destroy.
- The lifetime of the task object. It lives on
main's stack, from AddTask until long after it has exited.
Important
A task object must stay alive from AddTask until it has exited. Nothing checks this in a
release build. See Lifetimes.