I have some piece of code that is causing an error when it's run with Thread Sanitizer on:
bool Renderer::render(std::optional<int32_t> cancellationToken) {
const RenderWatcher renderWatcher{cancellationToken};
...
return Render(...
[&renderWatcher]() { return !renderWatcher.isRenderInProgress(); });
}
Inside RenderWatcher
I have a constructor that sets the cancellation token in a private field:
const std::optional<int32_t> cancellationToken;
And some getters:
bool RenderWatcher::isRenderInProgress() const {
if (!cancellationToken) {
return true;
}
...
}
The lambda [&renderWatcher]() { return !renderWatcher.isRenderInProgress(); }
is a boost::async
instance stored in a private field and asks about "can this render process be cancelled?".
The TSAN race is in RenderWatcher
constructor, when setting the cancellationToken, and the renderWatcher.isRenderInProgress
, which is reading cancellationToken
without a mutex.
Can I have a data race if RenderWatcher is a local variable but it's captured by reference in the lambda?
Capturing by value solves the race:
[renderWatcher]() { return !renderWatcher.isRenderInProgress(); }
Or protecting with mutex:
bool RenderWatcher::isRenderInProgress() const {
// Lock mutex here
if (!cancellationToken) {
return true;
}
...
}
Is this a real data race? How does capturing by reference or by value makes a difference?
Thanks.
stack-use-after-return
violation.