gpt4 book ai didi

c - PThread Mutex无法按预期工作

转载 作者:行者123 更新时间:2023-12-03 12:52:38 25 4
gpt4 key购买 nike

我正在使用互斥锁尝试将对代码的某些部分的访问限制为一个线程,但是似乎没有锁定一次并阻止其他线程,而是允许所有线程“锁定”。以下是我的代码,然后是输出的一部分,显示该代码无法正常工作。

//headers defined, etc

pthread_mutex_t queuemutex = PTHREAD_MUTEX_INITIALIZER;

// other code with various functions

int main(void) {

//unrelated code

threadinformation **threadArray = (threadinformation **)malloc( POOLSIZE * sizeof(threadinformation) );

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]); //thread is created here
currentThread->thread = thread;
joinArray[k] = thread;
}

//unrelated code

}

static void* readWriteToClient(void *inputcontent) {

while(1){

//unrelated code

pthread_mutex_lock(&queuemutex); //problem happens here

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

//unrelated code

}

}

输出。
Thread 0 got locked 
Thread 7 got locked
Thread 25 got locked
Thread 97 got locked
Thread 6 got locked
Thread 5 got locked
Thread 4 got locked
Thread 3 got locked
Thread 8 got locked
Thread 9 got locked
Thread 10 got locked
Thread 11 got locked
Thread 12 got locked
Thread 13 got locked
Thread 14 got locked
Thread 15 got locked
Thread 16 got locked
Thread 17 got locked
Thread 18 got locked
Thread 19 got locked
Thread 20 got locked
And so on...

最佳答案

没有问题。

pthread_cond_wait(&cond,&queuemutex);

等待条件变量释放互斥量。

关于c - PThread Mutex无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15078758/

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