Skip to content

Commit 4a7fece

Browse files
aLekSermarkmandel
andauthored
CPP SDK example code: join threads before return (agones-dev#1283)
Fix core dump on example code. Co-authored-by: Mark Mandel <mark.mandel@gmail.com>
1 parent b9d123d commit 4a7fece

1 file changed

Lines changed: 21 additions & 1 deletion

File tree

‎examples/cpp-simple/server.cc‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,32 @@
2121
#include <iostream>
2222
#include <thread>
2323

24+
std::atomic_int stop_threads(0);
25+
26+
class ThreadJoiner {
27+
public:
28+
explicit ThreadJoiner(std::thread t)
29+
: t_(std::move(t)) {}
30+
31+
~ThreadJoiner() {
32+
// Stop threads loop
33+
stop_threads.store(1);
34+
t_.join();
35+
}
36+
private:
37+
std::thread t_;
38+
};
39+
2440
// send health check pings
2541
void DoHealth(std::shared_ptr<agones::SDK> sdk) {
2642
while (true) {
2743
bool ok = sdk->Health();
2844
std::cout << "Health ping " << (ok ? "sent" : "failed") << "\n"
2945
<< std::flush;
3046
std::this_thread::sleep_for(std::chrono::seconds(2));
47+
if(stop_threads.load()) {
48+
return ;
49+
}
3150
}
3251
}
3352

@@ -41,7 +60,6 @@ void WatchUpdates(std::shared_ptr<agones::SDK> sdk) {
4160
<< std::flush;
4261
});
4362
}
44-
4563
int main() {
4664
std::cout << "C++ Game Server has started!\n"
4765
<< "Getting the instance of the SDK.\n"
@@ -57,6 +75,8 @@ int main() {
5775

5876
std::thread health(DoHealth, sdk);
5977
std::thread watch(WatchUpdates, sdk);
78+
ThreadJoiner h(std::move(health));
79+
ThreadJoiner w(std::move(watch));
6080

6181
std::cout << "Setting a label\n" << std::flush;
6282
grpc::Status status = sdk->SetLabel("test-label", "test-value");

0 commit comments

Comments
 (0)