LoginSignup
3
4

More than 5 years have passed since last update.

Multi-Consumer/Multi-Producer Blocking Queue実装

Last updated at Posted at 2014-03-15

セマフォ(Semaphore)または条件変数(Condition Variable)同期プリミティブを利用した、並行処理Blocking Queueの実装例(疑似コード)。

条件変数版

condition not_full;
condition not_empty;
mutex guard;

void queue(data item) {
    lock(guard);
    while (!has_empty_slot())
        cv_wait(not_full, guard);
    put(item);
    cv_broadcast(not_empty);
    unlock(guard);
}

data dequeue() {
    lock(guard);
    while (!has_avail_item())
        cv_wait(not_empty, guard);
    data item = pop();
    cv_broadcast(not_full);
    unlock(guard);
    return item;
}

セマフォ版

semaphore fill_count = 0;
semaphore empty_count = QUEUE_SIZE;
semaphore guard = 1; // or mutex

void queue(data item) {
    sem_down(empty_count);
    sem_down(guard);
    put(item);
    sem_up(guard);
    sem_up(fill_count);
}

data dequeue() {
   sem_down(fill_count);
   sem_down(guard);
   data item = pop();
   sem_up(guard);
   sem_up(empty_count);
   return item;
}

sem_up=V操作/signal操作
sem_down=P操作/wait操作

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4