Dave's Brain

Browse - programming tips - bottleneck

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

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); }
};

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 
}

Add a comment

Sign in to add a comment
Copyright © 2008, dave - Code on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License.