Skip to content

Instantly share code, notes, and snippets.

@nidefawl
Last active December 15, 2020 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nidefawl/076cf4274c767f7e0eedbbac99cd310e to your computer and use it in GitHub Desktop.
Save nidefawl/076cf4274c767f7e0eedbbac99cd310e to your computer and use it in GitHub Desktop.
Fixed
/* This crashes for me (line 19) */
#include <iostream>
#include <vector>
#include <thread>
#include <memory>
#include <chrono>
#include <mutex>
#include <assert.h>
struct mystruct_t {
int32_t nInvocation = 0;
~mystruct_t();
mystruct_t() = default;
};
mystruct_t::~mystruct_t() {
nInvocation++;
int nInvoke = nInvocation;
if (nInvoke > 1) {
/* destructor was invoked twice */
assert(0);
}
/* sleep is not necessary for crash */
//std::this_thread::sleep_for(std::chrono::microseconds(525));
}
std::recursive_mutex mutex;
std::shared_ptr<mystruct_t> globalPtr;
void thread1() {
for (;;) {
std::this_thread::sleep_for(std::chrono::microseconds(1000));
std::shared_ptr<mystruct_t> ptrNewInstance = std::make_shared<mystruct_t>();
{
std::lock_guard<std::recursive_mutex> lock(mutex);
globalPtr = ptrNewInstance;
}
}
}
void thread2() {
for (;;) {
std::shared_ptr<mystruct_t> pointerCopy;
{
std::lock_guard<std::recursive_mutex> lock(mutex);
pointerCopy = globalPtr;
}
}
}
int main()
{
std::thread t1;
t1 = std::thread([]() {
thread1();
});
std::thread t2;
t2 = std::thread([]() {
thread2();
});
for (int i = 0;; ++i) {
std::this_thread::sleep_for(std::chrono::microseconds(1000));
std::shared_ptr<mystruct_t> pointerCopy;
{
std::lock_guard<std::recursive_mutex> lock(mutex);
pointerCopy = globalPtr;
globalPtr = nullptr;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment