New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Thread-safety of cursors #118
Comments
No they are not thread-safe!
Mitigations depend on what you are trying to achieve. One option to have a cursor tree in another thread is to have a second cursor root (a For example: // this is the first store
auto io1 = boost::asio::io_context{};
auto store1 = lager::make_store<Action>(
Model(...),
lager::with_boost_asio_event_loop{io1.get_executor()});
// a secondary store just to have data consumed in another thread
auto io2 = boost::asio::io_context{};
auto store2 = lager::make_store<Model>(
Model(...),
lager::with_boost_asio_event_loop{io1.get_executor()},
lager::with_reducer([](auto&&, auto m) { return m; }));
// send data to second store when it changes in first store
store1.watch([&](auto m) { store2.dispatch(m); });
// each store has its own thread...
std::thread([&io1] { io1.run(); }).detach();
std::thread([&io2] { io2.run(); }).detach(); This is an example with |
Thank you, I'll try. |
I have been thinking that cursors are thread-safe, but it seems not the case.
Using this code to execute:
If cursors are thread-safe,
readertest
will always print out lines with 3000 same digits of 0 or 1 or 2, so the pipe should print out nothing. But in fact it occasionally print out lines like(the sequence is mostly 1 but contains some 2 in the middle) which means
reader.get()
gives us corrupted data.Does this mean we should not use cursors outside the thread that contains the event loop? In particular, the following operations:
reader.map(...).make()
in the main thread)get()
on a local cursor object (reader.get()
in the main thread)std::thread([reader2=reader] { reader2.get(); }).detach();
)Which of these are safe, considering the event loop is not running on the main thread?
If any of these are not safe, how can we mitigate the thread-unsafety here?
Thank you very much for your help.
The text was updated successfully, but these errors were encountered: