views:

67

answers:

4

I'm working a program that will have a bunch of threads processing data.

Each thread needs to grab the next available ID, increment that ID by 1 for the next thread and do this in a thread-safe way.

Is this an instance where I would use a mutex? Should I use a Queue.Synchronized instead and fill it up with all 300,000 ID's or is this unecessary?

Should I just have a single integer and somehow lock the retrieval and updating of that number so thread1 comes in, gets "20" as the next ID and then increments it to "21" while another thread is waiting?

What is the best-practice for this use-case?

+1  A: 

Nope.

Best way to do this is Interlocked.Increment().

Basically you can perform the increment in a threadsafe way without locking based on guarantees provided by the CPU architecture.

Spence
+2  A: 

This is probably the perfect candidate for Interlocked.Increment.

int id = 0;

int nextId = Interlocked.Increment(ref id); // returns the incremented value

The Increment is performed as an atomic operation and is thread-safe.

dtb
+4  A: 

You can do this without locking via Interlocked.Increment.

Just do this like so:

private static int value;
public static int Value
{
    get { return Interlocked.Increment(ref value); }
}

This will always return an incrementing integer, without locks, and with perfect threadsafety.

Reed Copsey
+1  A: 

Hi again ;)

You should look into the Interlocked class. It provides functionality for atomically incrementing the value of an integer.

spender