I am creating a multi-threaded application that uses double buffering, and I am trying to avoid a potential deadlock. The basic idea is that the clipboard stream blocks the write and read stream. However, the clipboard stream is fast, so locks will not remain blocked. Write and read streams are slower but efficiently allocate time fragments (target), since they block different mutexes. My question is a potential dead end with this design?
- 3 threads ... Thread A, Thread B and Thread C.
- 2 mutex ... Front Mutex and Mutex Back.
- Subject A fills the feedback buffer
- Thread B replaces the buffer.
- Stream C uses the front buffer.
- Thread A takes BackMutex, fills the back buffer, frees BackMutex.
- In thread C, theFrontMutex is taken, uses the front buffer, releases theFrontMutex.
- Thread B takes theBackMutex, theFrontMutex, swaps buffers, releases theBackMutex, frees Mutex Front
void *fill_back_buffer() {
while(1) {
if (0 != pthread_mutex_lock(&theBackMutex)) {
perror("Mutex lock failed (!!):");
exit(-1);
}
pthread_cond_wait(&theBackBufferRefresh, &theBackMutex);
if (0 != pthread_mutex_unlock(&theBackMutex)) {
perror("Mutex lock failed (!!):");
exit(-1);
}
pthread_cond_signal(&theBackBufferFull);
}
}
void *swap_buffers() {
while(1) {
if (0 != pthread_mutex_lock(&theBackMutex)) {
perror("Mutex lock failed (!!):");
exit(-1);
}
if (0 != pthread_mutex_lock(&theFrontkMutex)) {
perror("Mutex lock failed (!!):");
exit(-1);
}
pthread_cond_wait(&theBackBufferFull, &theBackMutex);
char* tmp;
tmp = theBufferAPtr;
theBufferAPtr = theBufferBPtr;
theBufferBPtr = tmp;
if (0 != pthread_mutex_unlock(&theFrontMutex)) {
perror("Mutex lock failed (!!):");
exit(-1);
}
if (0 != pthread_mutex_unlock(&theBackMutex)) {
perror("Mutex lock failed (!!):");
exit(-1);
}
pthread_cond_signal(&theBackBufferRefresh);
pthread_cond_signal(&theBufferSwapped);
}
}
int main(int argc, char *argv[]) {
pthread_cond_signal(&theBackBufferRefresh);
while(1) {
if (0 != pthread_mutex_lock(&theFrontMutex)) {
perror("Mutex lock failed (!!):");
exit(-1);
}
pthread_cond_wait(&theBufferSwapped, &theFrontMutex);
if (0 != pthread_mutex_unlock(&theFrontMutex)) {
perror("Mutex lock failed (!!):");
exit(-1);
}
}
}
source
share