我有一个C ++程序,其中我创建多个线程,并让他们访问共享阵列。
每次我想一个线程访问数组,我打电话
pthread_mutex_lock(&mutex);
访问阵列,然后调用
pthread_mutex_unlock(&mutex);
所有线程不断循环,直到他们已经访问数组若干倍。 因此,他们不只是访问数组一次,而是访问了好几遍。
现在,当我执行我的计划只是因为它是,无论哪个线程首先获取互斥体(通常是创建的第一个线程)执行,直到它完成,允许另一个线程访问前阵。
如果我添加了一个简单的睡眠()的背后
pthread_mutex_unlock(&mutex);
然后线程将交替访问阵列(这是我想要的)。 我宁可不要使用睡眠(),但是做到这一点。
据我所知,我相信这是发生了什么:
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.