lundi 7 mai 2018

thread sync using mutex and condition variable

I'm trying to implement an multi-thread job, a producer and a consumer. For example, see the code below,

mutex m;
condition_variable cv;

vector<int> Q;  // this is the queue the consumer will consume
vector<int> Q_buf;  // this is a buffer Q into which producer will fill new data directly

// consumer
void consume() {
  while (1) {
    if (Q.size() == 0) {
      unique_lock<mutex> lk(m);
      // notify producer to fill up the Q
      cv.wait(lk);
    }

    // for-loop to process the elems in Q
    ...
  }
}

// producer
void produce() {
  while (1) {
    // for-loop to fill up Q_buf
    ...

    // once Q_buf is fully filled, wait until consumer asks to give it a full Q
    unique_lock<mutex> lk(m);
    cv.wait(lk);
    Q.swap(Q_buf);  // replace the empty Q with the full Q_buf
    cv.notify_one();
  }
}

I'm not sure this the above code using mutex and condition_variable is the right way to implement my idea, please give me some advice!

Aucun commentaire:

Enregistrer un commentaire