How to make global data thread safe ? Please Help...

  • Thread starter Thread starter Kunal
  • Start date Start date
K

Kunal

Hi friends,

I seem to be stuck in a peculiar problem.

I have a public static class with public static members (different
array lists). The members are thus global in nature and accessible
across the namespace.

I have a worker function which is called asynchronously (so that there
are several instances running per second) and which reads the different
global members at different points of execution (not the entire set at
any one point).

I have a writer function which is used to set the global members and
this is the only one in the application writing to these variables. It
will write the entire set of globals when given control through a GUI
event.

I need a mechanism where if one instance of worker function is
accessing any of the global members and the writer function is called,
all instances of worker function (which I assume would be different
threads) should complete their read operation and wait before next read
(of another global member) until the writer function is finished
updating all the globals. This must also mean that the writer function
wait till all instances of read operation are complete and then go
ahead to update the variables.

I have gone through Lock, Mutex, Semaphore but feel quite confused
about the type of model that I should implement. Please help me.

Thanks n Regards,

Kunal
 
You're going to want to look at Monitor & ReaderWriterLock.

Your code is basically going to look like this:

public class MyClass
{
private static List<string> _myList = new List<String>();
private static object _syncLock = new object();
public static void AddName(string s)
{
lock(_syncLock)
{
_myList.Add(s);
}
}

public static bool DoesNameExist(string s)
{
lock(_syncLock)
{
foreach(string i in _myList)
{
if s.equals(i)
return true;
}
}
return false;
}
}

In all likleyhood, a lock will generally be faster and easier for you than a
ReaderWriterLock. It will almost certainly be "good enough".
 
Back
Top