我正在创建一个使用双缓冲的线程化应用程序,我试图避免潜在的死锁。主要思想是交换缓冲区线程锁定写入和读取线程。然而,交换缓冲区线程很快,所以锁不会长时间保持锁定状态。写入和读取线程较慢,但高效共享时间片(目标),因为它们锁定在不同的互斥锁上。我的问题是这种设计有潜在的僵局吗?C双缓冲区实现死锁?
- 3线程...线程A,线程B,和C.螺纹
- 2互斥...前互斥和后退的互斥。
- 线程A填充后缓冲器
- 线程B交换缓冲器。
- 线程C使用前端缓冲区。
- 线程A需要theBackMutex,填充后缓冲,释放theBackMutex。
- 线程C使用FrontMutex,使用前台缓冲区,释放FrontMutex。
- 线程B需要theBackMutex,theFrontMutex,切换缓冲区,释放theBackMutex,释放theFront互斥
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);
}
}
}
如果你不能工作,我们自己然后建立一个Petri网模型,并检查它的方式。 – 2011-03-15 20:17:45
我会检查一下,我以前从未使用过Petri网模型。谢谢。 – 2011-03-15 20:27:36
一旦你建立了你的模型,你可以将它导入到一个工具,并让工具找到你的死锁。漂亮的东西! – 2011-03-15 20:29:22