I (내 원래 코드에서 적응) 다음과 같은 소스 코드를했습니다 :pthread_mutex_unlock을하지 원자
#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
#include "pthread.h"
#define MAX_ENTRY_COUNT 4
int entries = 0;
bool start = false;
bool send_active = false;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condNotEmpty = PTHREAD_COND_INITIALIZER;
pthread_cond_t condNotFull = PTHREAD_COND_INITIALIZER;
void send()
{
for (;;) {
if (!start)
continue;
start = false;
for(int i = 0; i < 11; ++i) {
send_active = true;
pthread_mutex_lock(&mutex);
while(entries == MAX_ENTRY_COUNT)
pthread_cond_wait(&condNotFull, &mutex);
entries++;
pthread_cond_broadcast(&condNotEmpty);
pthread_mutex_unlock(&mutex);
send_active = false;
}
}
}
void receive(){
for(int i = 0; i < 11; ++i){
pthread_mutex_lock(&mutex);
while(entries == 0)
pthread_cond_wait(&condNotEmpty, &mutex);
entries--;
pthread_cond_broadcast(&condNotFull);
pthread_mutex_unlock(&mutex);
}
if (send_active)
printf("x");
}
int _tmain(int argc, _TCHAR* argv[])
{
pthread_t s;
pthread_create(&s, NULL, (void *(*)(void*))send, NULL);
for (;;) {
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&condNotEmpty, NULL);
pthread_cond_init(&condNotFull, NULL);
start = true;
receive();
pthread_mutex_destroy(&mutex);
mutex = NULL;
pthread_cond_destroy(&condNotEmpty);
pthread_cond_destroy(&condNotFull);
condNotEmpty = NULL;
condNotFull = NULL;
printf(".");
}
return 0;
}
다음과 같은 문제는 : 시간에서 송신 기능의 마지막 잠금 해제가되기 전에 완료되지 않습니다 시간 수신 방법이 계속됩니다. 원래 코드에서 뮤텍스는 작업을 수행 한 후에 삭제되는 객체에 있습니다. send 메소드가 마지막 잠금 해제로 끝나지 않았다면 뮤텍스는 유효하지 않으며 내 프로그램은 잠금 해제시 실패를 유발합니다.
프로그램을 실행하면 문제를 쉽게 재현 할 수 있습니다. "x"가 표시 될 때마다 수신 방법이 거의 완료되고 보내기 메서드가 잠금 해제 호출에 "중단"됩니다.
VS2008 및 VS2010으로 컴파일했습니다. 두 결과가 동일합니다.
pthread_mutex_unlock은 원자가 아니므로 문제가 해결됩니다. 이 문제를 어떻게 해결할 수 있습니까? 모든 의견은
안부
마이클
나는이 문제를 완전히 이해하고 있는지 확신 할 수는 없지만 의존하는 뮤텍스를 파괴하기 전에 send 스레드가 종료 될 때까지 기다릴 필요는 없다 ('pthread_join (s, NULL);') ? –
또한 정적 초기 화기'PTHREAD_MUTEX_INITIALIZER'와'pthread_mutex_init' 호출로 뮤텍스를 초기화 할 필요가 없습니다. (이미 초기화 된 뮤텍스를 초기화하려고하면 정의되지 않은 동작이 발생합니다.) –
보내기 스레드는 내 응용 프로그램에서 끝나지 않는 스레드입니다 (사실상 I/O 스레드입니다). – michael