Gee*_*_SO 3 c concurrency multithreading mutex pthreads
据我所知,互斥锁应该锁定一次,然后阻止其他人,直到释放,就像这样.

但是使用我的代码,似乎多个线程锁定了相同的互斥锁.我有一个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
Run Code Online (Sandbox Code Playgroud)
我的互斥锁全局定义在*.c文件的顶部,因为,
pthread_mutex_t queuemutex = PTHREAD_MUTEX_INITIALIZER;
Run Code Online (Sandbox Code Playgroud)
以下是相关的代码段.
//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;
}
Run Code Online (Sandbox Code Playgroud)
这里是所有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);
Run Code Online (Sandbox Code Playgroud)
我的精神力量表明这currentWaiting->status是最初的0.
既然如此,您的代码进入while循环并等待条件变量.
等待条件变量会解锁互斥锁,直到等待完成,允许其他线程获取它.
| 归档时间: |
|
| 查看次数: |
270 次 |
| 最近记录: |