18.2. Providing Thread-Safe Access to Class Members
Problem
You need to provide thread-safe access through accessor functions to an internal member variable.
The following NoSafeMemberAccess class shows three methods: ReadNumericField, IncrementNumericField, and ModifyNumericField. While all of these methods access the internal numericField member, the access is currently not safe for multithreaded access:
public static class NoSafeMemberAccess
{
private static int numericField = 1;
public static void IncrementNumericField( )
{
++numericField;
}
public static void ModifyNumericField(int newValue)
{
numericField = newValue;
}
public static int ReadNumericField( )
{
return (numericField);
}
}Solution
NoSafeMemberAccess could be used in a multithreaded application, and therefore it must be made thread-safe. Consider what would occur if multiple threads were calling the IncrementNumericField method at the same time. It is possible that two calls could occur to IncrementNumericField while the numericField is updated only once. In order to protect against this, you will modify this class by creating an object that you can lock against in critical sections of the code:
public static class SaferMemberAccess
{
private static int numericField = 1;
private static object syncObj = new object( );
public static void IncrementNumericField( )
{
lock(syncObj) {
++numericField;
}
}
public static void ModifyNumericField(int newValue)
{
lock(syncObj) {
numericField = newValue;
} } public static int ReadNumericField( ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access