Reputation: 3534
Why the compiler complain about this code snippet when -std=c++11 -lpthread -fsanitize=thread -ltsan
are enabled?
#include <iostream>
#include <memory>
#include <thread>
#include <vector>
#include <mutex>
std::mutex mtx;
void checkAndUse(std::weak_ptr<int> weakPtr) {
std::lock_guard<std::mutex> lck(mtx);
if (auto sharedPtr = weakPtr.lock()) {
std::cout << "Using shared resource: " << *sharedPtr << std::endl;
} else {
std::cout << "Shared resource has been destroyed." << std::endl;
}
}
int main() {
auto sharedPtr = std::make_shared<int>(1);
std::weak_ptr<int> weakPtr = sharedPtr;
std::vector<std::thread> threads;
for (int i = 0; i < 10; ++i) {
threads.emplace_back(checkAndUse, weakPtr);
}
{
std::lock_guard<std::mutex> lck(mtx);
sharedPtr.reset(); // Destroy the shared resource
}
for (auto& thread : threads) {
thread.join();
}
return 0;
}
Here is what the compiler complains:
FATAL: ThreadSanitizer: unexpected memory mapping 0x71f4f1272000-0x71f4f1700000
Upvotes: 4
Views: 98