Run Code
|
Code Wall
|
Users
|
Misc
|
Feedback
|
About
|
Login
|
Theme
|
Privacy
6.2 Parallelism: locks
//6.2 Parallelism: locks using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading; namespace Rextester { public class Program { static object _list_lock = new object(); public static void Main(string[] args) { List<string> list = new List<string>() {"one", "two"}; //Documentation on List<T> says that it's not thread-safe meaning you can't read/write to it from multiple threads (or undefined bahaviour may occur) //Therefore we must use locks. Locks are special mechanism so that only one thread can aquire lock at a time. Locks use variables to lock on //(and it's best to use something like private static object variable named clearly what data structure it's guarding, like shown here). ThreadPool.QueueUserWorkItem(f => { lock(_list_lock) //this statement will block if some other thread has aquired the lock and haven't yet released { list.Add("four"); //now we have aquired a lock and shall release it only when execution will get out of this scope } }); ThreadPool.QueueUserWorkItem(f => { lock(_list_lock) { list.Add("five"); } }); lock(_list_lock) { list.ForEach(Console.WriteLine); //even iteration is not thread-safe while some other thread is writing to list, so we use lock here too } Thread.Sleep(3000); //let's wait for other threads to end, //although it's not garanteed that they actually will terminate after 3 seconds and not even garanteed that they would start by then. //We have queued them for execution and they will be executed as soon as possible, but on an idle system 3 sec is more than enough lock(_list_lock) { list.ForEach(Console.WriteLine); } } } }
run
|
edit
|
history
|
help
0
Please
log in
to post a comment.
Get Distinct value using Group By , Having , Count in DataTable C#
User Defined Exception (Inherited from built-in Exception class)
sadfghjklö
Add char to non-numerical words only
Fórum ➡ Prime numbers implemented using LINQ statements AND using FOR loop ♦
Get a webpage - the sync way
ss
Convert string to TimeSpan in C#
Product, Category, Composition and Inheritance
ATM
Please log in to post a comment.