Skip to content

Commit

Permalink
Fixed PeriodicTaskExecutor fork handler (elastic#1209)
Browse files Browse the repository at this point in the history
  • Loading branch information
intuibase committed Aug 22, 2024
1 parent 446b469 commit 7e9d8eb
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
13 changes: 9 additions & 4 deletions agent/native/libcommon/code/PeriodicTaskExecutor.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@
#include <stop_token>
#include <thread>
#include <vector>
#include <cstring>
#include <memory>

namespace elasticapm::php {


class PeriodicTaskExecutor : public ForkableInterface {
private:
auto getThreadWorkerFunction() {
Expand All @@ -30,7 +31,6 @@ class PeriodicTaskExecutor : public ForkableInterface {

~PeriodicTaskExecutor() {
shutdown();

if (thread_.joinable()) {
thread_.join();
}
Expand Down Expand Up @@ -62,12 +62,17 @@ class PeriodicTaskExecutor : public ForkableInterface {

void prefork() final {
shutdown();
thread_.join();
if (thread_.joinable()) {
thread_.join();
}
}

void postfork([[maybe_unused]] bool child) final {
working_ = true;

mutex_.lock();
thread_ = std::thread(getThreadWorkerFunction());
mutex_.unlock();
pauseCondition_.notify_all();
}

Expand Down Expand Up @@ -107,8 +112,8 @@ class PeriodicTaskExecutor : public ForkableInterface {
std::chrono::milliseconds sleepInterval_ = std::chrono::milliseconds(20);
std::vector<task_t> periodicTasks_;
worker_init_t workerInit_;
std::thread thread_;
std::mutex mutex_;
std::thread thread_;
std::condition_variable pauseCondition_;
bool working_ = true;
bool resumed_ = false;
Expand Down
10 changes: 8 additions & 2 deletions agent/native/libcommon/test/PeriodicTaskExecutorTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,13 @@ TEST(PeriodicTaskExecutorTest, resumeAfterFork) {

periodicTaskExecutor_.setInterval(20ms);

pthread_atfork(fh_prepare, fh_parent, fh_child);

static bool pthread_atfork_called = false;

if (!pthread_atfork_called) {
pthread_atfork(fh_prepare, fh_parent, fh_child);
pthread_atfork_called = true;
}

periodicTaskExecutor_.resumePeriodicTasks();
std::this_thread::sleep_for(100ms);
Expand All @@ -60,7 +66,7 @@ TEST(PeriodicTaskExecutorTest, resumeAfterFork) {

ASSERT_GE(counter.load(), 13); // should be 15 in ideal world
if (pid == 0) {
exit(0);
exit(testing::Test::HasFailure());
}
}

Expand Down

0 comments on commit 7e9d8eb

Please sign in to comment.