Multi-Core and Hyper-Threading Technology 7
7-13
Example 7-3 Thread Function for an Interlaced Producer Consumer Model
// master thread starts the first iteration, the other thread must wait
// one iteration
void producer_consumer_thread(int master)
{
int mode = 1 - master; // track which thread and its designated buffer index
unsigned int iter_num = workamount >> 1;
unsigned int i=0;
iter_num += master & workamount & 1;
if (master) // master thread starts the first iteration
{
produce(buffs[mode],count);
Signal(sigp[1-mode],1); // notify the producer task in follower thread
// that it can proceed
consume(buffs[mode],count);
Signal(sigc[1-mode],1);
i = 1;
}
for (; i < iter_num; i++)
{
WaitForSignal(sigp[mode]);
produce(buffs[mode],count); // notify the producer task in other thread
Signal(sigp[1-mode],1);
WaitForSignal(sigc[mode]);
consume(buffs[mode],count);
Signal(sigc[1-mode],1);
}
}