views:

105

answers:

3

A staticfunction retUnique() return me a unique value. My question is that if there are many users who are using the same function at a given point of time, what happens? Is there a best practice to make sure that each users accessing this static function simultaneously get a unique value and also do not face threading issues.

Can one give me an example.

A: 

There is nothing special about static functions that make them more or less safe to use on multiple threads. Instead, you need to examine the data which the function accesses and modifies, and make sure that it still respects the integrity of that data when called concurrently.

Here's an example that might be relevant to your question:

private static int myUniqueID = 1;
public static int GetFreshUniqueID()
{
    lock(someObject)
    {
        return myUniqueID++;
    }
}

The key in this case to keeping it thread-safe is locking the function in some synchronization context so that we don't run into a situation where two threads get the same ID before either of them get around to incrementing it. Your situation may vary.

mquander
what does (someobject) refer to?
Viks
You might want to refer to the docs for the lock statement: http://msdn.microsoft.com/en-us/library/c5kehkcz(VS.71).aspx
mquander
mquander beat me to it (and I'm having trouble getting code to format properly). You probably want the lock object to be like: private static readonly object sUniqueLock = new object(); declared right after myUniqueID. And check out the docs for more.
Rob Parker
A: 

Isn't this a simple synchronization problem?

Apply a lock at the beginning of the function and release it at end.

Sesh
A: 

Assuming you want to simply return a unique incrementing integer value, the simplest safe approach is probably to use a private static counter and a private static lock object. Something like:

private static int s_UniqueCounter; // starts at 0 by default
private static readonly object s_UniqueCounterLock = new object();

public static int GetUnique()
{
    lock (s_UniqueCounterLock)
    {
        s_UniqueCounter++;
        return s_UniqueCounter;
    }
}

It's up to you to make sure the particular lock object is used to protect any other access to the static counter member (which is why they are declared private, of course, so the class which owns them controls any access). It probably shouldn't be accessed anywhere else, for this use, but you might have something look at the current value to see how many times it has been called. That should probably be protected by the lock as well (to make sure the result is current):

internal static int QueryUniqueCount() // or this could be private, or public
{
    lock (s_UniqueCounterLock)
    {
        return s_UniqueCounter;
    }
}
Rob Parker