Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can multiple threads add items to Concurrent collections EXACTLY at the same time?

I am trying to figure out concurrent collections in C#.

ConcurrentBag, ConcurrentDictionary and ConcurrentQueue.

Is it possible for multiple threads to add items to them EXACTLY at the same time? Or they wait one after the other?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried to examine their source code, but I really couldn’t tell for sure.

I see here that there is an answer for C++, but I would like to know if this is the case also for C#?

>Solution :

It’s not provable, at the software level. Meaning that you can’t write a program that can prove or disprove the theory that two items can be inserted by two threads in the same collection at exactly the same time.

One attempt to prove it would be to have a third thread acting as the observer, that would enumerate the collection in a tight loop while the other two threads are doing the two concurrent insertions. Let’s say that the observer thread observed zero elements in one enumeration and two elements in the next enumeration, what would this prove? A thread can be suspended by the operating system at any moment for a duration measured in milliseconds, so you haven’t learn anything conclusive about the issue at hand. The two insertion might have happened exactly the same time, or milliseconds apart from one another, who knows?

If you want to answer this question at the hardware level, then at this level the concept of "collection" does not exist. You have registers, CPU instructions, memory chips etc. There are no software objects to talk about at this level.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading