Skip to content

Commit

Permalink
feat:add timefd for mac
Browse files Browse the repository at this point in the history
  • Loading branch information
chenxuan520 committed Dec 26, 2024
1 parent c0c4ee8 commit 841d154
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 9 deletions.
39 changes: 36 additions & 3 deletions src/cppnet/timer/timer.cpp
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@

#include "timer.hpp"
#include "../utils/const.hpp"

#ifdef __linux__
#include <sys/timerfd.h>
#elif __APPLE__
#include <dispatch/dispatch.h>
#include <thread>
#endif

#include <unistd.h>
Expand All @@ -23,8 +22,9 @@ int TimerSocket::Init(int sec, int nsec) {
Reset(sec, nsec);
status_ = kInit;
return kSuccess;

#elif __APPLE__
return kNotSupport;
return Reset(sec, nsec);
#else
return kNotSupport;
#endif
Expand All @@ -40,6 +40,39 @@ int TimerSocket::Reset(int sec, int nsec) {

timerfd_settime(fd_, 0, &ts, NULL);
return kSuccess;

#elif __APPLE__
if (send_fd_ > 0) {
Close();
}

int pipe_fd[2] = {-1, -1};
if (pipe(pipe_fd) < 0) {
return kSysErr;
}

fd_ = pipe_fd[0];
send_fd_ = pipe_fd[1];
status_ = kInit;

std::thread(
[](int send_fd, int sec, int nsec) {
uint64_t exp;
TimerSocket soc(send_fd);
while (true) {
std::this_thread::sleep_for(
std::chrono::nanoseconds((long long)(sec * 1e9) + nsec));
auto rc = soc.Write(&exp, sizeof(uint64_t));
if (rc <= 0) {
// close socket
break;
}
}
},
send_fd_, sec, nsec)
.detach();

return kSuccess;
#else
return kNotSupport;
#endif
Expand Down
11 changes: 11 additions & 0 deletions src/cppnet/timer/timer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,17 @@ class TimerSocket : public Socket {
inline int IOWrite(const void *buf, size_t len, int flag = 0) override {
return ::write(fd_, buf, len);
}

#ifdef __APPLE__
public:
int Close() override {
Socket::Close();
return Socket(send_fd_).Close();
}

private:
int send_fd_ = -1;
#endif
};

} // namespace cppnet
6 changes: 1 addition & 5 deletions src/test/timer/timer_test.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,6 @@ using namespace cppnet;
using namespace std;

TEST(Timer, CreateTimer) {
#ifdef __APPLE__
SKIP();
#endif

#ifdef WIN32
SKIP();
#endif
Expand Down Expand Up @@ -61,6 +57,6 @@ TEST(Timer, CreateTimer) {
// 1e7 = 10ms, 100ms = 1e8
// 1s = 1e9
DEBUG("timer event count: " << count);
MUST_TRUE(count > 90 && count < 110,
MUST_TRUE(count >= 80 && count <= 110,
"timer event count wrong " + to_string(count));
}
2 changes: 1 addition & 1 deletion src/third_party/cpptest
Submodule cpptest updated from 1b9a2d to 7844d3

0 comments on commit 841d154

Please sign in to comment.