Skip to content

Commit

Permalink
Create threadsafe_impl.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
mayank4519 authored Nov 7, 2022
1 parent 81c686e commit 8d1d3bd
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions singleton/threadsafe_impl.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#include <iostream>
#include <mutex>
#include <future>

using namespace std;
std::mutex m;

class S{
public:
static S& getInstance() {
std::lock_guard<std::mutex> mylock(m);
if (s == nullptr)
s = new S();
return *s;
}
private:
S() = default;
~S() = default;
S(const S&) = delete;
S& operator=(const S&) = delete;
static S *s;
};

S* S::s = nullptr;

void Instance() {
S::getInstance();
}

int main()
{
auto f1 = std::async(std::launch::async, Instance);
auto f2 = std::async(std::launch::async, Instance);
auto f3 = std::async(std::launch::async, Instance);

f1.get();
f2.get();
f3.get();

return 0;
}

0 comments on commit 8d1d3bd

Please sign in to comment.