Skip to content

Commit 291e9dd

Browse files
authored
fix: wait until AutomaticallyCreatedBackgroundThreads start (#8452)
Don't return from the `AutomaticallyCreatedBackgroundThreads` ctor until we know that each thread functor has been invoked. Some users hold their client objects, which own `BackgroundThreads` objects, in such a way that the client is not destroyed during process shutdown, and therefore that its background threads are not joined. This means that it is possible for a `std::thread` to be running but still within the standard library (i.e., not yet in the user functor) while global objects are being destroyed. In the case at hand, the standard library was in the process of setting up thread-specific data via `pthread_setspecific()`, when its key appears to have disappeared from underneath it, resulting in MemorySanitizer errors. This probably isn't the only shutdown race waiting to bite us, but it is one we've seen in practice.
1 parent 3cdd834 commit 291e9dd

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

google/cloud/internal/background_threads_impl.cc

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
// limitations under the License.
1414

1515
#include "google/cloud/internal/background_threads_impl.h"
16+
#include "google/cloud/future.h"
1617
#include "google/cloud/log.h"
1718
#include <algorithm>
1819
#include <system_error>
@@ -26,7 +27,15 @@ AutomaticallyCreatedBackgroundThreads::AutomaticallyCreatedBackgroundThreads(
2627
std::size_t thread_count)
2728
: pool_(thread_count == 0 ? 1 : thread_count) {
2829
std::generate_n(pool_.begin(), pool_.size(), [this] {
29-
return std::thread([](CompletionQueue cq) { cq.Run(); }, cq_);
30+
promise<void> started;
31+
auto thread = std::thread(
32+
[](CompletionQueue cq, promise<void>& started) {
33+
started.set_value();
34+
cq.Run();
35+
},
36+
cq_, std::ref(started));
37+
started.get_future().wait();
38+
return thread;
3039
});
3140
}
3241

0 commit comments

Comments
 (0)