C++ timer example
source link: https://gist.github.com/ytx21cn/385ba27c1a5a8b753cb272692a8df6f9
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Instantly share code, notes, and snippets.
#include <iostream> #include <set>
extern "C" { #include "unistd.h" #include <sys/timerfd.h> }
int main() { std::set<int> timerFds;
fd_set readfds; FD_ZERO(&readfds);
size_t n = 10; int maxFd = 0; for (size_t i = 1; i <= n; ++i) { int fd = timerfd_create(CLOCK_REALTIME, 0); maxFd = std::max(fd, maxFd);
itimerspec spec; spec.it_value = { (long)i, 0 }; spec.it_interval = { 0, 0 }; timerfd_settime(fd, 0, &spec, nullptr);
timerFds.emplace(fd); }
timespec timeout = { 2, 0 };
while (!timerFds.empty()) { for (const int& fd : timerFds) { FD_SET(fd, &readfds); }
int availableFds = pselect(maxFd + 1, &readfds, nullptr, nullptr, &timeout, nullptr); std::cout << "Available file descriptors: " << availableFds << std::endl;
if (availableFds > 0) { for (const int& fd : timerFds) { if (FD_ISSET(fd, &readfds)) { std::cout << "Found file descriptor: " << fd << std::endl;
int val; read(fd, &val, sizeof(val)); std::cout << "Read from file descriptor " << fd << ", value: " << val << std::endl;
itimerspec spec = { {0, 0}, {0, 0} }; timerfd_settime(fd, 0, &spec, nullptr); } } } else { break; } }
return 0; }
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK