Game Development Reference
In-Depth Information
mutable CRITICAL_SECTION m_cs;
};
class ScopedCriticalSection : public GCC_noncopyable
{
public:
ScopedCriticalSection( CriticalSection & csResource)
: m_csResource( csResource)
{ m_csResource.Lock(); }
ScopedCriticalSection() { m_csResource.Unlock(); }
private:
CriticalSection & m_csResource;
˜
};
If you had a bit of code that needed to be thread safe, you would first declare a
CriticalSection object and use the ScopedCriticalSection object in your
threads to block until the critical section was free.
CriticalSection g_Cs;
void ThreadSafeFunction()
{
ScopedCriticalSection(&g_Cs);
// do dangerous things here!
}
Because the ScopedCriticalSection object locks the critical section in the con-
structor and unlocks it in the destructor, the code in the same scope of this object is
now thread safe and easy to read at the same time. You
'
ll see this class used in a
better example shortly.
Interesting Threading Problems
There are a number of interesting threading problems you should be aware of: racing,
starvation, and deadlock.
Racing is a condition where two or more threads are reading or writing shared data,
and the final result requires the threads to run in a precise order, which can never be
guaranteed. The classic problem is the writer-reader problem, where a writer thread
fills a buffer, and a reader thread processes the buffer. If the two threads aren
'
t syn-
chronized properly, the reader will overtake the writer and read garbage.
The solution to this problem is easy with a shared count of bytes in the buffer, chan-
ged only by the writer thread using a critical section.
 
 
Search WWH ::




Custom Search