mirror of
https://github.com/boostorg/cobalt.git
synced 2026-01-19 04:02:16 +00:00
85 lines
2.3 KiB
Plaintext
85 lines
2.3 KiB
Plaintext
[#thread]
|
|
== cobalt/thread.hpp
|
|
|
|
The thread type is another way to create an environment that is similar to `main`, but doesn't use a `signal_set`.
|
|
|
|
[source,cpp]
|
|
----
|
|
cobalt::thread my_thread()
|
|
{
|
|
auto exec = co_await cobalt::this_coro::executor; // <1>
|
|
asio::steady_timer tim{exec, std::chrono::milliseconds(50)}; // <2>
|
|
co_await tim.async_wait(cobalt::use_op); // <3>
|
|
co_return 0;
|
|
}
|
|
----
|
|
<1> get the executor `thread` running on
|
|
<2> Use it with an asio object
|
|
<3> `co_await` an cobalt operation
|
|
|
|
To use a thread you can use it like a `std::thread`:
|
|
|
|
[source,cpp]
|
|
----
|
|
int main(int argc, char * argv[])
|
|
{
|
|
auto thr = my_thread();
|
|
thr.join();
|
|
return 0;
|
|
}
|
|
----
|
|
|
|
A thread is also an `awaitable` (including cancellation).
|
|
|
|
[source,cpp]
|
|
----
|
|
cobalt::main co_main(int argc, char * argv[])
|
|
{
|
|
auto thr = my_thread();
|
|
co_await thr;
|
|
co_return 0;
|
|
}
|
|
----
|
|
|
|
NOTE: Destructing a detached thread will cause a hard stop (`io_context::stop`) and join the thread.
|
|
|
|
WARNING: Nothing in this library, except for awaiting a <<thread>> and <<spawn>>, is thread-safe.
|
|
If you need to transfer data across threads, you'll need a thread-safe utility like https://www.boost.org/doc/libs/master/doc/html/boost_asio/reference/experimental__basic_concurrent_channel.html[`asio::concurrent_channel`].
|
|
You cannot share any cobalt primitives between threads,
|
|
with the sole exception of being able to <<spawn, spawn>> a <<task, task>> onto another thread's executor.
|
|
|
|
=== Executor
|
|
[#thread-executor]
|
|
|
|
It will also create an `asio::io_context` to run on, which you can get through the `this_coro::executor`.
|
|
It will be assigned to the `cobalt::this_thread::get_executor()` .
|
|
|
|
=== Memory Resource
|
|
[#thread-allocator]
|
|
|
|
It also creates a memory resource that will be used as a default for internal memory allocations.
|
|
It will be assigned to the `thread_local` to the `cobalt::this_thread::get_default_resource()`.
|
|
|
|
[#thread-outline]
|
|
=== Outline
|
|
|
|
|
|
[source,cpp]
|
|
----
|
|
include::../../include/boost/cobalt/thread.hpp[tag=outline]
|
|
----
|
|
<1> Supports <<interrupt_await>>
|
|
<2> Always forward cancel
|
|
|
|
[#thread-promise]
|
|
=== Promise
|
|
|
|
The thread promise has the following properties.
|
|
|
|
- <<promise_cancellation_base>>
|
|
- <<promise_throw_if_cancelled_base>>
|
|
- <<enable_awaitables>>
|
|
- <<enable_await_allocator>>
|
|
- <<enable_await_executor>>
|
|
|