gpt4 book ai didi

C双缓冲区实现死锁?

转载 作者:行者123 更新时间:2023-12-02 00:34:15 25 4
gpt4 key购买 nike

我正在创建一个使用双缓冲的线程应用程序,我正在尝试避免潜在的死锁。主要思想是交换缓冲区线程锁定写入和读取线程。然而,交换缓冲区线程很快,因此锁不会长时间保持锁定状态。写入和读取线程速度较慢,但​​可以有效地共享时间片(目标),因为它们锁定在不同的互斥锁上。我的问题是这种设计是否存在潜在的僵局?

  • 3 个线程...线程 A、线程 B 和线程 C。
  • 2 个互斥...前互斥和后互斥。

  • 线程 A 填充后台缓冲区
  • 线程 B 交换缓冲区。
  • 线程 C 使用前台缓冲区。

  • 线程 A 获取 BackMutex,填充后台缓冲区,释放 BackMutex。
  • 线程 C 获取 FrontMutex,使用前台缓冲区,释放 FrontMutex。
  • 线程 B 获取 BackMutex、FrontMutex,交换缓冲区,释放 BackMutex,释放 Front Mutex

void *fill_back_buffer() {
while(1) {
if (0 != pthread_mutex_lock(&theBackMutex)) {
perror("Mutex lock failed (!!):");
exit(-1);
}
//should we get new data for back buffer?
pthread_cond_wait(&theBackBufferRefresh, &theBackMutex);
//fill back buffer
if (0 != pthread_mutex_unlock(&theBackMutex)) {
perror("Mutex lock failed (!!):");
exit(-1);
}
//hey we done filling the back buffer!
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);
}
//do we have new data in the back buffer?
pthread_cond_wait(&theBackBufferFull, &theBackMutex);

//swap buffers
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);
}
//hey please get more data!
pthread_cond_signal(&theBackBufferRefresh);
//hey you can use front buffer now!
pthread_cond_signal(&theBufferSwapped);

}
}

int main(int argc, char *argv[]) {
//initial fill of the back buffer
pthread_cond_signal(&theBackBufferRefresh);
while(1) {
if (0 != pthread_mutex_lock(&theFrontMutex)) {
perror("Mutex lock failed (!!):");
exit(-1);
}
pthread_cond_wait(&theBufferSwapped, &theFrontMutex);
//use the front buffer and do stuff with it
if (0 != pthread_mutex_unlock(&theFrontMutex)) {
perror("Mutex lock failed (!!):");
exit(-1);
}
}
}

最佳答案

条件变量应该用于表示某些(受互斥锁保护的)共享数据的状态发生变化。你不能单独使用它们。考虑一下如果一个线程在另一个线程等待该条件之前发出条件信号会发生什么。

关于C双缓冲区实现死锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5317470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com