Mithrax
Mithrax

Reputation: 7809

How can I have many threads that need to know the next ID to process and then increment that number safely?

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?

Upvotes: 0

Views: 264

Answers (4)

spender
spender

Reputation: 120480

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

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564451

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.

Upvotes: 4

dtb
dtb

Reputation: 217313

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.

Upvotes: 2

Spence
Spence

Reputation: 29332

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.

Upvotes: 1

Related Questions