Skip to content

Commit

Permalink
threadsafety_singleton
Browse files Browse the repository at this point in the history
  • Loading branch information
HendEmad committed May 20, 2024
1 parent 96dd6f3 commit 3637833
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Singleton/Counter.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@ class Counter {
}
};


22 changes: 22 additions & 0 deletions ThreadSafety_Singleton/Client.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#include<iostream>
#include<string>
#include <thread>
#include "Counter.h"
using namespace std;

int main() {
thread task1([]() {
Counter* counter1 = Counter::GetInstance();
counter1 -> addOne();
cout << "Counter1: " + to_string(counter1 -> count) << endl;
});

thread task2([]() {
Counter* counter2 = Counter::GetInstance();
counter2 -> addOne();
cout << "Counter2: " + to_string(counter2 -> count) << endl;
});

task1.join();
task2.join();
}
6 changes: 6 additions & 0 deletions ThreadSafety_Singleton/Counter.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#include "Counter.h"
#include <mutex>
using namespace std;

Counter* Counter::instance = nullptr;
mutex Counter::lockObj;
21 changes: 21 additions & 0 deletions ThreadSafety_Singleton/Counter.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#include <mutex>

class Counter {
static Counter* instance;
static std::mutex lockObj;
Counter() {}

public:
int count = 0;
static Counter* GetInstance() {
std::lock_guard<std::mutex> guard(lockObj); // lock the mutex
if(instance == nullptr)
instance = new Counter();
return instance;
}

void addOne() {
count++;
}

};
Binary file added ThreadSafety_Singleton/multi.exe
Binary file not shown.

0 comments on commit 3637833

Please sign in to comment.