1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
#include <assert.h>
#include <errno.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "log.h"
#include "thread.h"
using namespace std;
Thread::~Thread() {}
void Thread::run()
{
should_stop_status = false;
pthread_create(&worker_thread, nullptr, &Thread::do_work_thunk, this);
}
void Thread::stop()
{
{
lock_guard<mutex> lock(should_stop_mutex);
should_stop_status = true;
}
wakeup();
if (pthread_join(worker_thread, nullptr) == -1) {
log_perror("pthread_join");
exit(1);
}
}
void *Thread::do_work_thunk(void *arg)
{
Thread *thread = reinterpret_cast<Thread *>(arg);
// Block SIGHUP; only the main thread should see that.
// (This isn't strictly required, but it makes it easier to debug that indeed
// SIGUSR1 was what woke us up.)
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGHUP);
int err = pthread_sigmask(SIG_BLOCK, &set, nullptr);
if (err != 0) {
errno = err;
log_perror("pthread_sigmask");
exit(1);
}
// Block SIGUSR1, and store the old signal mask.
sigemptyset(&set);
sigaddset(&set, SIGUSR1);
err = pthread_sigmask(SIG_BLOCK, &set, &thread->sigset_without_usr1_block);
if (err != 0) {
errno = err;
log_perror("pthread_sigmask");
exit(1);
}
// Call the right thunk.
thread->do_work();
return nullptr;
}
bool Thread::wait_for_activity(int fd, short events, const struct timespec *timeout_ts)
{
pollfd pfd;
pfd.fd = fd;
pfd.events = events;
for ( ;; ) {
int nfds = ppoll(&pfd, (fd == -1) ? 0 : 1, timeout_ts, &sigset_without_usr1_block);
if (nfds == -1 && errno == EINTR) {
return false;
}
if (nfds == -1) {
log_perror("poll");
usleep(100000);
continue;
}
assert(nfds <= 1);
return (nfds == 1);
}
}
void Thread::wakeup()
{
pthread_kill(worker_thread, SIGUSR1);
}
bool Thread::should_stop()
{
lock_guard<mutex> lock(should_stop_mutex);
return should_stop_status;
}
|