bit

マルチスレッド+libevent

スレッドとファイルディスクリプタが一対一のパターン。

typedef struct {
  pthread_t th;
  struct event_base * ev_base;
  struct event ev;
} worker_t;

static worker_t * workers;

static void _reset_event_handler(worker_t * w, int fd);

static void _ev_receive_data(int fd, short event, void * arg) {
  w = (worker_t *)arg;

  if (event & EV_READ) {
    ...
  } else if (...) {
    ...
  }

  _reset_event_handler(w, fd);
}

static void _reset_event_handler(worker_t * w, int fd) {
  ...

  event_set(&w->ev, fd, EV_READ | ..., _ev_receive_data, (void *)w);
  event_base_set(w->ev_base, &w->ev);
  rs = event_add(&w->ev, ..);
  if (rs != 0) {
    ...
  }
}

static void * _worker_main(void * arg) {
  ...

  w = (worker_t *)arg;
  w->ev_base = event_init();

  fd = open(...);

  _reset_event_handler(w, fd);

  event_base_loop(w->ev_base);

  event_del(&w->ev);
  event_base_free(w->ev_base);

  close(fd);
}

int main() {
  workers = (worker_t *)calloc(...);

  for (i = 0; i < NB_WORKERS; ++i) {
    w = workers[i];
    pthread_create(&w.th, NULL, _worker_main, &w);
  }

  for (i = 0; i < NB_WORKERS; ++i) {
    w = workers[i];
    pthread_join(&w.th, NULL);
  }

  free(workers);

  return(0);
}