Dave's Brain

Browse - programming tips - foolproof critical section class

Date: 2007nov6, Code Written: 2000
Keywords: critical, section, sections

Q.  How do you make sure only one thread has access to something?

A.  The classic way is a "critical section" and Windows provides
this.  For safely, I think its crucial to make a class where
the destructor is sure to be done ... avoiding a mistake where
some code might forget to tell the world that section is available
when its done (causing a deadlock).

Often a read-write lock is better because it allows simultaneous
readers.  We have another posting about them.

My classes go like this:

class CBottleNeck
{
	CRITICAL_SECTION crit;

public:
	CBottleNeck() { InitializeCriticalSection(&crit); }
	~CBottleNeck() { DeleteCriticalSection(&crit); }
	void Enter() { EnterCriticalSection(&crit); }
	void Leave() { LeaveCriticalSection(&crit); }

	CBottleNeck(const CBottleNeck &) // Copy constructor
	{
		// Can not copy a critial section, need to make a new one
		InitializeCriticalSection(&crit);
	}

	const CBottleNeck &operator=(const CBottleNeck &) // Assignment operator
	{
		// Can not copy a critial section, need to make a new one
		InitializeCriticalSection(&crit);
		return *this;
	}
};

class CBottleNeckSession
{
	CBottleNeck	*m_neck;

public:
	CBottleNeckSession(CBottleNeck *neck)
	{
		m_neck = neck;
		if (m_neck != NULL) { m_neck->Enter(); }
   	}

   	~CBottleNeckSession()
   	{
		if (m_neck != NULL) { m_neck->Leave(); }
	}
};

Use like this:

CBottleNeck		special_place;

{
	CBottleNeckSession(&special_place);

	// Do stuff 
}
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2012, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.