4 ms·
I'm only sitting here, waiting for my thread_locals to get broken.... or maybe they are handled magically somehow
by malkia 4y ago
I'm only sitting here, waiting for my thread_locals to get broken.... or maybe they are handled magically somehow
- jcelerier 4y ago.. why would they be broken ? coroutines are not related to threads
- grogers 4y agoI think the point is that if the coroutine suspends it could be resumed on a different thread. So you don't really want to mix thread locals and coroutines.
- jcelerier 4y agoI mean, for sure but that's not a property of coroutines, any callback system can do that e.g. if you have this code with boost: #include <boost/asio.hpp> #include <chrono> #include <vector> #include <thread> #include <iostream> std::mutex print_mutex; int main() { using namespace boost::asio; using namespace std::literals; io_context io_context(20); auto work_guard = make_work_guard(io_context); for(int i = 0; i < 100; i++) { post(io_context, [&] { thread_local int x = 0; int z = x++; std::lock_guard _{print_mutex}; std::cout << z << "\n"; }); } std::vector<std::jthread> v; for(int i = 0; i < 20; i++) v.emplace_back([&] { io_context.run_for(2s); }); } i hope you don't expect the output to be "0, 1, 2, ..., 99"
- deleted 4y ago[deleted]
- malkia 4y agostate, e.g. assuming that there is single flow of operations, and nothing gets swapped out (logically). This breaks with co-operative scheduling systems - e.g. task thread while waiting on I/O (for example) gets reused for some other task, hence they get to see the same thread_local, and somewhere someone assumed "thread_local" == "task_local" of sorts (but not).
- jstimpfle 4y agoIn Win32 at least, there is "FLS", Fiber Local Storage. But Fibers (Windows speak for coroutines, but not sure how they relate to C++ coroutines) are generally considered to be not worth the complexity.
- Matthias247 4y agoFibers would be stackful coroutines (every coroutine gets its own stack memory, and local variables inside a coroutine are placed onto that stack). Whereas C++ coroutines are stackless - local data in those gets placed into a magic object that is created somewhere by the compiler. Stackful vs stackless comes with a few pro's and con's - e.g. it's often argued that stackless requires less memory. However stackful coroutines can allow for preemption at arbitrary points instead of just at yield points.
- eco 4y agoTo expand on what you said, they recently decided to work on stackful coroutines for C++26 now that C++23 is final. You can just use one of the many libraries if you don't want to wait for the standard library version. Stackful coroutines didn't require any compiler support, unlike stackless so they've be available for a long time (stackless have also been around since C++20).