Last active
October 16, 2021 21:23
-
-
Save ytxmobile98/385ba27c1a5a8b753cb272692a8df6f9 to your computer and use it in GitHub Desktop.
C++ timer example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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 }; | |
| sleep(10); | |
| while (1) { | |
| 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; | |
| uint64_t 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; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment