I want to test a scenario where I check weak_ptr for validity and return shared_ptr. between checking and returning if some other thread delete the shared_ptr we would face exception. I tried to simulate same scenario using windows sleep or cout but it seems to be not working. code is as follows:
#include <iostream>
#include <thread>
#include <windows.h>
#include <mutex>
using namespace std;
mutex m;
struct Block
{
int * p_ = nullptr;
Block() { p_ = new int[10000]; refCount_++; }
~Block() { delete[] p_; _p = nullptr; }
int refCount_;
};
struct Weak_ptr
{
Block * p_ = nullptr;
Weak_ptr() { p_ = new Block(); }
void Addref() { p_->refCount_++; }
void release() { delete[] p_; p_ = nullptr; cout << "\nptr deleted\n"; }
};
void funct1(int x, Weak_ptr *ptr)
{
cout << "\nin thread 1 \n";
cout << "\nSleep thread 1\n";
//Sleep(x)
for (int i = 0; i < x; i++)
cout << ".";
cout << "\nAwake thread 1\n";
ptr->release();
}
void funct2(int x, Weak_ptr *ptr)
{
m.lock();
cout << "\nin thread 2 \n";
if (ptr->p_)
{
cout << "\nptr checked \n";
//Sleep(x)
for (int i = 0; i < x; i++)
cout << "|";
cout << "\nusing ptr in t2\n";
ptr->Addref();
}
else
{
cout << "\ncheck succeeded \n";
}
m.unlock();
}
int main()
{
Weak_ptr s;
thread t1(&funct1, 2000, &s);
thread t2(&funct2, 4000, &s);
t1.join();
t2.join();
}