Skip to content

CPP wrapper class to add exclusivity (thread-safety) to an existing class.

License

Notifications You must be signed in to change notification settings

harveypham/exclusive

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

exclusive

Header-only implementation of exclusive_obj and exclusive_ptr that turns a class to thread-safe (exlusive). The differences between exclusive_obj and exclusive_ptr are how the underlining class is defined within the wrapper classes.

Assuming that the following class is defined:

class Sample
{
public:
	Sample(const string& name, int value = 0) : name_(name), value_(value) {}

	const string& Name() const { return name_; }
	int Value() const { return value_; }

	void SetName(const string& name) { name_ = name; }
	void Inc(void) { ++value_; }
	void Dec(void) { --value_; }

private:
	string name_;
	int value_;
};

Basic Usage

  1. Declaring resource
using ExcSamplePtr = exclusive_ptr<Sample>;

ExcSamplePtr sample{ "Sample" }; // Construction using the same syntax as class Sample
  1. Accesing resource directly with implicit locking
// Each invocation implicitly acquires lock, invoke the underline method, then
// release lock
sample->Inc();
std::string name = sample.Name();
int value = sample.Value();
  1. Explictly acquire the underling resource
auto lockedSample = sample.acquire(); // Lock 
// Access locked resource via lockedSample
lockedSample->Inc();
std::cout << lockedSample->Name() << ": " << lockedSample->Value() << endl;
// Unlock when lockedSample is out of scope

Using a different locking mechanism

By default, the wrapper classes use std::mutex and std::lock_guard<mutex> to handle locking. Users can specify different locking mechanism:

// Using ATL critical section instead
locked_ptr<Sample, ATL::CCriticalSection, ATL::CCritSecLock> sample2 { "Sample 2" };

About

CPP wrapper class to add exclusivity (thread-safety) to an existing class.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published