| description | Learn more about: Walkthrough: Adapting Existing Code to Use Lightweight Tasks | ||
|---|---|---|---|
| title | Walkthrough: Adapting Existing Code to Use Lightweight Tasks | ||
| ms.date | 04/25/2019 | ||
| helpviewer_keywords |
|
||
| ms.assetid | 1edfe818-d274-46de-bdd3-e92967c9bbe0 |
This topic shows how to adapt existing code that uses the Windows API to create and execute a thread to use a lightweight task.
A lightweight task is a task that you schedule directly from a concurrency::Scheduler or concurrency::ScheduleGroup object. Lightweight tasks are useful when you adapt existing code to use the scheduling functionality of the Concurrency Runtime.
Before you start this walkthrough, read the topic Task Scheduler.
The following example illustrates typical usage of the Windows API to create and execute a thread. This example uses the CreateThread function to call the MyThreadFunction on a separate thread.
[!code-cppconcrt-windows-threads#1]
This example produces the following output.
Parameters = 50, 100
The following steps show how to adapt the code example to use the Concurrency Runtime to perform the same task.
- Add a
#includedirective for the header file concrt.h.
[!code-cppconcrt-migration-lwt#2]
- Add a
usingdirective for theconcurrencynamespace.
[!code-cppconcrt-migration-lwt#3]
- Change the declaration of
MyThreadFunctionto use the__cdeclcalling convention and to returnvoid.
[!code-cppconcrt-migration-lwt#4]
- Modify the
MyDatastructure to include a concurrency::event object that signals to the main application that the task has finished.
[!code-cppconcrt-migration-lwt#5]
- Replace the call to
CreateThreadwith a call to the concurrency::CurrentScheduler::ScheduleTask method.
[!code-cppconcrt-migration-lwt#6]
- Replace the call to
WaitForSingleObjectwith a call to the concurrency::event::wait method to wait for the task to finish.
[!code-cppconcrt-migration-lwt#7]
-
Remove the call to
CloseHandle. -
Change the signature of the definition of
MyThreadFunctionto match step 3.
[!code-cppconcrt-migration-lwt#8]
- At the end of the
MyThreadFunctionfunction, call the concurrency::event::set method to signal to the main application that the task has finished.
[!code-cppconcrt-migration-lwt#9]
- Remove the
returnstatement fromMyThreadFunction.
The following completed example shows code that uses a lightweight task to call the MyThreadFunction function.
[!code-cppconcrt-migration-lwt#1]