mirror of
https://github.com/facebook/react-native.git
synced 2026-11-18 20:19:07 +00:00
Hold lock while changing atomic running_ in TaskDispatchThread (#54817)
Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/54817 Changelog: [Internal] Fixed a bug in TaskDispatchThread. According to https://en.cppreference.com/w/cpp/thread/condition_variable.html: > Even if the shared variable is atomic, it must be modified while owning the mutex to correctly publish the modification to the waiting thread. So we need to own a lock when changing running_ in quit(). Otherwise, there is a chance that signal will get lost, which leads to deadlock on quit(). Also I did a minor refactoring by updating running_.compare_exchange_strong() to running_.exchange(). Reviewed By: javache Differential Revision: D88640446 fbshipit-source-id: 364864d58787650a23d8f835b7874bda8d762673
This commit is contained in:
1 parent
9011316fc6
commit
64bb0d5510
2 files changed
+13
-6
No files matched your search
@@ -70,7 +70,7 @@ void TaskDispatchThread::runAsync(
|
||||
if (!running_) {
|
||||
return;
|
||||
}
|
||||
std::lock_guard<std::mutex> guard(queueLock_);
|
||||
std::lock_guard<std::mutex> guard(mutex_);
|
||||
auto dispatchTime = std::chrono::system_clock::now() + delayMs;
|
||||
queue_.emplace(dispatchTime, std::move(task));
|
||||
loopCv_.notify_one();
|
||||
@@ -91,9 +91,16 @@ void TaskDispatchThread::runSync(TaskFn&& task) noexcept {
|
||||
}
|
||||
|
||||
void TaskDispatchThread::quit() noexcept {
|
||||
bool expected = true;
|
||||
if (!running_.compare_exchange_strong(expected, false)) {
|
||||
return;
|
||||
{
|
||||
/*
|
||||
We should hold lock even when changing atomic variable to correctly
|
||||
publish the modificatino to the waiting thread
|
||||
from: https://en.cppreference.com/w/cpp/thread/condition_variable.html
|
||||
*/
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
if (!running_.exchange(false)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
loopCv_.notify_one();
|
||||
@@ -107,7 +114,7 @@ void TaskDispatchThread::loop() noexcept {
|
||||
folly::setThreadName(threadName_);
|
||||
}
|
||||
while (running_) {
|
||||
std::unique_lock<std::mutex> lock(queueLock_);
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
loopCv_.wait(lock, [&]() { return !running_ || !queue_.empty(); });
|
||||
|
||||
while (!queue_.empty()) {
|
||||
|
||||
@@ -61,7 +61,7 @@ class TaskDispatchThread {
|
||||
|
||||
void loop() noexcept;
|
||||
|
||||
std::mutex queueLock_;
|
||||
std::mutex mutex_;
|
||||
std::condition_variable loopCv_;
|
||||
std::priority_queue<Task> queue_;
|
||||
std::atomic<bool> running_{true};
|
||||
|
||||
Reference in new issue
Block a user