Skip to content

Commit 247ea40

Browse files
committed
add thread safety part in async
1 parent 54ea01c commit 247ea40

1 file changed

Lines changed: 22 additions & 0 deletions

File tree

tutorials/async.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,28 @@ arc::Future<> coro() {
248248
}
249249
```
250250

251+
### Thread safety
252+
253+
Remember that **all** async code runs in separate threads, meaning that any interaction with Cocos or GD will likely lead to a crash unless done correctly. For most cases, like spawning a web request and then handling the result, `async::spawn` and `async::TaskHolder` already provide simple ways to run a callback in the main thread. If this isn't enough for you, there are also two ways to run a piece of code in the main thread, depending on whether you need to wait for it to complete:
254+
255+
```cpp
256+
// The classic queueInMainThread, can be used from anywhere
257+
geode::queueInMainThread([] {
258+
log::debug("cocos is safe here :)");
259+
});
260+
261+
// If you are inside a coroutine and need to wait for the callback to complete
262+
co_await async::waitForMainThread<void>([] {
263+
log::debug("cocos is safe here :)");
264+
});
265+
266+
// Unlike queueInMainThread, this also allows you to return values!
267+
std::optional<int> value = co_await async::waitForMainThread<int>([] {
268+
log::debug("cocos is safe here :)");
269+
return 42;
270+
});
271+
```
272+
251273
## Enabling features
252274
253275
To reduce compile times, mods by default only include essential features of Arc (core and time utilities). You can opt into using other features by adding these lines in your CMakeLists.txt

0 commit comments

Comments
 (0)