2013-02-26 2 views
3

내가 아는 한, 뮤텍스는 한 번만 잠근 다음 해제 될 때까지 다른 블록을 차단해야합니다. 여러 스레드가 같은 뮤텍스를 잠그는처럼 무수한 많은 시간 잠금

enter image description here

하지만 내 코드

, 그것은 보인다. 스레드 풀이 10이므로 확실하게 9가 차단되고 1이 잠길 것입니다. 그러나 나는이 산출물을 얻는다.

Thread 0 got locked 
Thread 1 got locked 
Thread 3 got locked 
Thread 4 got locked 
Thread 2 got locked 
Thread 5 got locked 
Thread 6 got locked 
Thread 7 got locked 
Thread 8 got locked 
Thread 9 got locked 

내 뮤텍스는

pthread_mutex_t queuemutex = PTHREAD_MUTEX_INITIALIZER; 

그리고 여기에 관련 코드 세그먼트이며, 같은 * .c 인 파일의 맨 위에 전역으로 정의된다.

//In the main function which creates all the threads 
int k; 
for (k = 0; k < POOLSIZE; k++) { 
    pthread_t thread; 
    threadinformation *currentThread = (threadinformation *)malloc(sizeof(threadinformation)); 
    currentThread->state = (int *)malloc(sizeof(int)); 
    currentThread->state[0] = 0; 
    currentThread->currentWaiting = currentWaiting; 
    currentThread->number = k; 
    threadArray[k] = currentThread; 
    pthread_create(&thread, NULL, readWriteToClient, threadArray[k]); 
    currentThread->thread = thread; 
    joinArray[k] = thread; 
} 

그리고 여기에 10 개의 스레드가 모두 잠기는 코드 세그먼트가 있습니다.

pthread_mutex_lock(&queuemutex); 

fprintf(stderr,"Thread %d got locked \n",threadInput->number); 

while((threadInput->currentWaiting->status) == 0){ 
    pthread_cond_wait(&cond, &queuemutex); 
    fprintf(stderr,"Thread %d got signalled \n",threadInput->number); 
} 

connfd = threadInput->currentWaiting->fd; 
threadInput->currentWaiting->status = 0; 
pthread_cond_signal(&conncond); 
pthread_mutex_unlock(&queuemutex); 
+0

'int retcode = pthread_mutex_lock (& ​​queuemutex); assert (retcode == 0);' – Sebivor

+1

'currentWaiting'이란 무엇입니까? 또는 더 구체적으로'currentWaiting-> status'의 초기 값은 무엇입니까? – Hasturkun

답변

7

내 초능력은 currentWaiting->status가 처음 0 것을 제안한다.

코드가 while 루프에 들어가고 조건 변수를 기다립니다.

조건 변수를 대기하면 대기가 완료 될 때까지 뮤텍스가 잠금 해제되어 다른 스레드가이를 획득 할 수 있습니다.

+0

+1 그게 정확해야합니다. [pthread_cond_wait :] (http://linux.die.net/man/3/pthread_cond_wait)'이 함수는 뮤텍스를 원자 적으로 해제하고 조건 변수 cond에서 호출 스레드를 차단하도록합니다. ' – Mike

+0

최상급, 그렇지 않으면 뮤텍스 로직이 의미가 없습니다. 매우 일반적으로 말해서 코드 덩어리가 여러 스레드에 의해 실행되는 동안 mutex 내부에 cond_wait을 갖는 것이 좋습니다. 내 프로그램에 문제가있는 것 같지 않습니다. 그냥 실망했습니다! :) –

+0

완벽한 답변. 당신은 당신의 공감을 어디서 났습니까? 힘? ;) – didierc