Spring 2021
Instructors Roz Cyrus and Jerry Cain
PDF
static void writer(char buffer[]) {
cout << oslock << "Writer: ready to write." << endl << osunlock;
for (size_t i = 0; i < 320; i++) { // 320 is 40 cycles around the circular buffer of length 8
char ch = prepareData();
buffer[i % 8] = ch;
cout << oslock << "Writer: published data packet with character '" << ch << "'." << endl << osunlock;
}
}
static void reader(char buffer[]) {
cout << oslock << "\t\tReader: ready to read." << endl << osunlock;
for (size_t i = 0; i < 320; i++) { // 320 is 40 cycles around the circular buffer of length 8
char ch = buffer[i % 8];
processData(ch);
cout << oslock << "\t\tReader: consumed data packet " << "with character '" << ch << "'." << endl << osunlock;
}
}
int main(int argc, const char *argv[]) {
char buffer[8];
thread w(writer, buffer);
thread r(reader, buffer);
w.join();
r.join();
return 0;
}
int main(int argc, const char *argv[]) {
char buffer[8];
semaphore fullBuffers, emptyBuffers(8);
thread w(writer, buffer, ref(fullBuffers), ref(emptyBuffers));
thread r(reader, buffer, ref(fullBuffers), ref(emptyBuffers));
w.join();
r.join();
return 0;
}
static void writer(char buffer[], semaphore& full, semaphore& empty) {
cout << oslock << "Writer: ready to write." << endl << osunlock;
for (size_t i = 0; i < 320; i++) { // 320 is 40 cycles around the circular buffer of length 8
char ch = prepareData();
empty.wait(); // don't try to write to a slot unless you know it's empty
buffer[i % 8] = ch;
full.signal(); // signal reader there's more stuff to read
cout << oslock << "Writer: published data packet with character '" << ch << "'." << endl << osunlock;
}
}
static void reader(char buffer[], semaphore& full, semaphore& empty) {
cout << oslock << "\t\tReader: ready to read." << endl << osunlock;
for (size_t i = 0; i < 320; i++) { // 320 is 40 cycles around the circular buffer of length 8
full.wait(); // don't try to read from a slot unless you know it's full
char ch = buffer[i % 8];
empty.signal(); // signal writer there's a slot that can receive data
processData(ch);
cout << oslock << "\t\tReader: consumed data packet " << "with character '" << ch << "'." << endl << osunlock;
}
}