pthread_mutex更新不够快,所以一个线程会“锁定”锁。

pthread_mutex更新不够快,所以一个线程会“锁定”锁。

问题描述:

我有一个C++程序,我创建多个线程并让他们访问共享数组。pthread_mutex更新不够快,所以一个线程会“锁定”锁。

每次我想一个线程访问数组,我叫

pthread_mutex_lock(&mutex); 

访问数组 ,然后调用

pthread_mutex_unlock(&mutex); 

的所有线程不断循环,直到他们已经访问数组一定次数。因此,他们不只是访问一次数组,而是访问它几次。

现在,当我执行我的计划只是因为它是,无论哪个线程首先获取互斥体(通常是创建的第一个线程)执行,直到它完成,允许另一个线程访问前阵。

如果我添加一个简单的睡眠()后面

pthread_mutex_unlock(&mutex); 

然后线程将交替访问阵列(这是我想要的)。我宁愿不必使用sleep()来实现这一点。

据我所知,我相信这是发生了什么事:

Thread A locks the mutex and begins accessing the array 
Thread B tries to lock the mutex but finds its locked, therefore it waits 
Thread A finishes with the array and unlocks the mutex 
Thread A loops and relocks the mutex before Thread B realizes that Thread A unlocked the matrix 

因此线程A继续访问阵列,直到它访问了N次,即可完成与线程B访问阵列的n次

反正是有使线程等待(互斥锁解锁),更新速度更快,只要它的解锁获取锁?
我宁愿上面的输出是沿着线的东西更多:

Thread A locks the mutex and begins accessing the array 
Thread B tries to lock the mutex but finds its locked, therefore it waits 
Thread A finishes with the array and unlocks the mutex 
Thread B sees the mutex is unlocked and locks it 
Thread A loops and tries to lock the mutex, but finds its locked, therefore it waits 
... etc. 

相反的sleep()你可以在pthread_yield()/sched_yield()看看,这将导致线程A在放弃CPU获取互斥前再次释放它之后。互斥体不排队,不保证公平。

或者,使用条件变量指示其他线程。