gpt4 book ai didi

c - 多次互斥锁定

转载 作者:太空狗 更新时间:2023-10-29 16:02:18 26 4
gpt4 key购买 nike

据我所知,互斥量应该锁定一次然后阻塞其他直到被释放,就像这样。

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

我的互斥量在 *.c 文件的顶部全局定义为,

pthread_mutex_t queuemutex = PTHREAD_MUTEX_INITIALIZER;

这里是相关的代码段。

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

最佳答案

我的灵能表明 currentWaiting->status 最初是 0

由于是这种情况,您的代码进入 while 循环并等待条件变量。

等待条件变量解锁互斥量直到等待完成,允许其他线程获取它。

关于c - 多次互斥锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15089326/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com