Fastest way to pass data between threads

433 Views Asked by At

I'm not asking about the most idiomatic way using Background workers or thread pool or the TPL.

I'm trying to find out what approaches are the fastest when it comes to passing data from one thread to another using .NET

I'm currently playing around with a ring buffer with a write index and a read index. This way, I don't have any thread synchronization at all except atomic operations on updating read/write index. (I'm not 100% sure, but reading and ++ on integers are atomic in .NET, right? or can an integer be overwritten halfway when one thread reads it?)

                         Write Index
                              V
index 0 [_][_][_][_][_][_][_][_][_][_][_] --> higher index
               ^
           Read Index

Is this a reasonable approach when it comes to thread to thread communication?

I'm not using it for any real project, I just want to get a better grip on what works and what don't here.

[edit] Ok, I'm up for public shaming:

https://gist.github.com/rogeralsing/8121376

How many holes are there in that code?

1

There are 1 best solutions below

1
On

I think it depends on how you define "fastest" and "between threads". I think ConcurrentBag<T> is a really nice way. If i remember correctly the implementation uses some kind of linked list to reduce the scope of most locks so it becomes more scalable. Is it fast between 2 simple threads? you need to check, but it utilizes your cores so your application as a whole will run fast.