Skip to content
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

Fix for race in ZooKeeper when joining send_thread/receive_thread #48849

Merged
merged 2 commits into from
Apr 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 6 additions & 13 deletions src/Common/ZooKeeper/ZooKeeperImpl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -299,11 +299,8 @@ ZooKeeper::~ZooKeeper()
{
finalize(false, false, "Destructor called");

if (send_thread.joinable())
send_thread.join();

if (receive_thread.joinable())
receive_thread.join();
send_thread.join();
receive_thread.join();
}
catch (...)
{
Expand Down Expand Up @@ -365,11 +362,8 @@ ZooKeeper::ZooKeeper(
{
tryLogCurrentException(log, "Failed to connect to ZooKeeper");

if (send_thread.joinable())
send_thread.join();

if (receive_thread.joinable())
receive_thread.join();
send_thread.join();
receive_thread.join();

throw;
}
Expand Down Expand Up @@ -914,8 +908,7 @@ void ZooKeeper::finalize(bool error_send, bool error_receive, const String & rea
}

/// Send thread will exit after sending close request or on expired flag
if (send_thread.joinable())
send_thread.join();
send_thread.join();
}

/// Set expired flag after we sent close event
Expand All @@ -932,7 +925,7 @@ void ZooKeeper::finalize(bool error_send, bool error_receive, const String & rea
tryLogCurrentException(log);
}

if (!error_receive && receive_thread.joinable())
if (!error_receive)
receive_thread.join();

{
Expand Down
26 changes: 24 additions & 2 deletions src/Common/ZooKeeper/ZooKeeperImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -255,8 +255,30 @@ class ZooKeeper final : public IKeeper
Watches watches TSA_GUARDED_BY(watches_mutex);
std::mutex watches_mutex;

ThreadFromGlobalPool send_thread;
ThreadFromGlobalPool receive_thread;
/// A wrapper around ThreadFromGlobalPool that allows to call join() on it from multiple threads.
class ThreadReference
{
public:
const ThreadReference & operator = (ThreadFromGlobalPool && thread_)
{
std::lock_guard<std::mutex> l(lock);
thread = std::move(thread_);
return *this;
}

void join()
{
std::lock_guard<std::mutex> l(lock);
if (thread.joinable())
thread.join();
}
private:
std::mutex lock;
ThreadFromGlobalPool thread;
};

ThreadReference send_thread;
ThreadReference receive_thread;

Poco::Logger * log;

Expand Down