c++ producer-consumer problem

I have a project involving where the file size and a file name is put into the console and must print line by line everything within the file. This needs to be achieved using a shared bounded buffer(in this case a simple string array) and two threads, the consumer and producer. Mutexes or/and semaphores also need to be used so that the buffer can be properly accessed. How would I achieve this task? I am stumped on where to start should I make a class? Should I use <pthread> or <threads>? If anyone could suggest what they think is the optimal way of doing this task it would be much appreciated.
If you can use https://www.cplusplus.com/reference/multithreading/, then use it.

Before you start on reading whole files, think about a simple test case
1
2
3
4
5
6
7
8
9
10
11
12
13
14
consumer() {
  while ( sb ) {
    sb.extract(s)
    print(s)
  }
}

void producer() {
  string words[] = { "The","cat","sat","on","the","mat" };
  for ( auto &&s : words ) {
    sb.insert(s)
  }
  sb.done()
}

Instance a 'sb' with only 3 slots.

Think about
- what should insert do when the buffer is full
- what should extract do when the buffer is empty
when the buffer is full the producer shouldn't produce any more so maybe it should lose access to the buffer and if the buffer is empty the consumer shouldn't consume anything. I think I have to use a mutex or semaphore to achieve this but I am a bit unsure on which to use. @salem thanks for the help so far by the way
It really boils down to whether you want to force each thread to wait inside the sb when the internal buffer is full/empty (as appropriate), or return a status full/empty (as appropriate) so the caller can decide what to do.

Returning a status is perhaps better, because they may have something else to be getting on with while the shared buffer does it's thing.
Topic archived. No new replies allowed.