Geesh_SO
Geesh_SO

Reputation: 2206

Mutex locking numerous times

As far as I know, mutexes should lock once and then block others until freed, like this.

enter image description here

But with my code, it seems like multiple threads are locking the same mutex. I have a thread pool of 10, so surely 9 should block and 1 should lock. But I get this output.

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 

My mutex is defined globally at the top of *.c file as,

pthread_mutex_t queuemutex = PTHREAD_MUTEX_INITIALIZER;

And here are relevant code segments.

    //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;
}

And here is the segment of code in which all 10 threads seem to get the lock.

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);

Upvotes: 3

Views: 436

Answers (1)

Hasturkun
Hasturkun

Reputation: 36402

My psychic powers suggest that currentWaiting->status is initially 0.

Since that is the case, your code enters the while loop and waits on the condition variable.

Waiting on the condition variable unlocks the mutex until the wait completes, allowing the other threads to acquire it.

Upvotes: 7

Related Questions