I have an application where I want multiple threads to read a list. I want to update the list with new data periodically. When the list is updated, I figure I can create a new list and replace it with the old one. Example:
private List<string> _list = new List<string>();
private void UpdateList()
{
var newList = new List<string>(QueryList(...));
_list = newList;
}
private void ThreadRun()
{
foreach (var item in _list)
{
// process item...
}
}
In the UpdateList method, a new list is created and the _list reference is swapped with the new list. From my thinking, any existing thread will still hold the reference to the old list (which is OK for me), any new thread will pick up the new list. Eventually, all threads will end and the old list will be eventually garbage collected. Is there any locking required in this code, or is there anything I need to take care of to ensure safe multi-threaded access?
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.
C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.
The letter c was applied by French orthographists in the 12th century to represent the sound ts in English, and this sound developed into the simpler sibilant s.
To be sure neither staleness nor optimisations hurt you, use Interlocked.Exchange()
to update the field. Then you'll have an appropriate memory barrier on the write, without the expense of having volatile
on every read.
You're making instances of the list immutable and it is only mutable state that causes problems.
Your code is fine, but you should consider marking _list
as volatile
. This would mean that all reads get the latest version and the compiler / jitter / cpu won't optimise away any reads.
Alternatively, you could put a Thread.MemoryBarrier()
just before you assign the new list to make sure that all writes to the new list are committed before you publish it, but it's not a problem on x86 architecture.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With