이중 버퍼링을 사용하는 스레드 된 응용 프로그램을 만들고 잠재적 인 교착 상태를 피하려고합니다. 주 아이디어는 스왑 버퍼 스레드가 쓰기 및 읽기 스레드를 잠그는 것입니다. 그러나 스왑 버퍼 스레드가 빠르므로 잠금이 오래 잠긴 상태로 유지되지 않습니다. 쓰기 및 읽기 스레드는 느리지 만 다른 뮤텍스를 잠그기 때문에 시간 조각을 효율적으로 (목표) 공유합니다. 제 질문은이 디자인에 잠재적으로 교착 상태가 있습니까?C 이중 버퍼 구현 교착 상태?
- 3 스레드 ... 스레드 A, 스레드 B 및 C
- 2 뮤텍스 ... 전면 뮤텍스와 뒤로 뮤텍스를 스레드.
- 스레드 A는
- 스레드 B 버퍼 스왑 백 버퍼를 채운다.
- 스레드 C는 프론트 버퍼를 사용합니다.
- 스레드 A가 theBackMutex 소요 백 버퍼를 채우고, theBackMutex 릴리즈.
- 스레드 C는 theFrontMutex를 사용하고 프론트 버퍼를 사용하여 theFrontMutex를 해제합니다.
- 스레드 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);
}
}
}
우리 자신을 조작 할 수 없다면 페트리 네트 모델을 만들고 그런 식으로 확인하십시오. –
나는 이것을 살펴볼 것이다. 나는 전에 페트리 네트 모델을 사용한 적이 없다. 감사. –
모델을 만든 후에는 도구로 가져 와서 교착 상태를 찾을 수 있습니다. 꽤 산뜻한 재료! –