ThreadSanitizer告诉我这段代码中有数据竞争,但我没有看到它。看起来很简单;我正在锁定所有对变量的访问的互斥锁。它实际上是不安全的,还是TS被某种方式愚弄了?
bool AccessBool(pthread_mutex_t mutex, bool *value)
{
bool result;
pthread_mutex_lock(&mutex);
result = *value;
pthread_mutex_unlock(&mutex);
return result;
}
void SetBool(pthread_mutex_t mutex, bool *value, bool newValue)
{
pthread_mutex_lock(&mutex);
*value = newValue;
pthread_mutex_unlock(&mutex);
}
void WaitForQueue(dispatch_queue_t queue)
{
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, NULL);
// Some queued tasks may need to also perform tasks on the main thread, so
// simply waiting on the queue could cause a deadlock.
const CFRunLoopRef loop = CFRunLoopGetCurrent();
__block bool keepLooping = true;
// Loop because something else might quit the run loop.
do {
CFRunLoopPerformBlock(loop, kCFRunLoopCommonModes, ^{
dispatch_async(queue, ^{
CFRunLoopStop(loop);
SetBool(mutex, &keepLooping, false);
});
});
CFRunLoopRun();
} while (AccessBool(mutex, &keepLooping));
pthread_mutex_destroy(&mutex);
}