C# Threading: Mutual exclusion (via Monitor Class)
Observe the following faulty snippet from this post:
using System; using System.Threading; using System.IO; class Program { static void Main(string[] args) { for (int i = 0; i < 3; i++) { Thread thread = new Thread(new ThreadStart(ThreadMain)); thread.Name = String.Concat("Thread - ", i); thread.Start(); } } static void ThreadMain() { // Simulate Some work Thread.Sleep(500); // Access a shared resource / critical section WriteToFile(); } static void WriteToFile() { String ThreadName = Thread.CurrentThread.Name; Console.WriteLine("{0} using resource", ThreadName); try { using (StreamWriter sw = new StreamWriter("1.txt", true)) { sw.WriteLine(ThreadName); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
Like earlier explained, what we've got here is three threads trying to write to a file, which fails horribly since we cant concurrently write to the same file.
Previously we used the Mutex class to resolve this issue, but we won't always need the power of the Mutex class (by which we can achieve a global lock on resources within our processes) - a lot (if not most) of the time the Monitor class will suffice.
Observe the monitor based solution:
static object locker = new object(); static void WriteToFile() { String ThreadName = Thread.CurrentThread.Name; Console.WriteLine("{0} using resource", ThreadName); Monitor.Enter(locker); try { using (StreamWriter sw = new StreamWriter("1.txt", true)) { sw.WriteLine(ThreadName); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { Monitor.Exit(locker); Console.WriteLine("{0} releasing resource", ThreadName); } }
Basically each thread will wait until the locker object gets released by the first thread that achieved a lock, before it attempts to write to our file.
Alternatively we can simply make use of the lock statement, which neatly wraps the Monitor.Enter - Monitor.Exit statements like this:
static object locker = new object(); static void WriteToFile() { String ThreadName = Thread.CurrentThread.Name; Console.WriteLine("{0} using resource", ThreadName); lock (locker) { try { using (StreamWriter sw = new StreamWriter("1.txt", true)) { sw.WriteLine(ThreadName); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
We do however have more control (if needed) over our lock using the Monitor (instead of the lock statement), like visible in the next crude snippet:
if (Monitor.TryEnter(locker, 500)) { try { Console.WriteLine("Lock Achieved"); Thread.Sleep(1000); // Simulate work } catch { } finally { Monitor.Exit(locker); } } else { Console.WriteLine("Lock Failed"); }
If a thread can't achieve a lock within our defined 500 milliseconds, we've got the ability to handle it - instead of just waiting forever (or whenever garbage collection eventually happens).
Note:
Generally fields that are read/written within multiple threads, should be read/written within a lock.
Vocabulary
Atomicity / Atomically
From the greek word "atomos" which means indivisible (early scientists prematurely named the atom after this word - which they used to consider to be the smallest building block of matter).
In context of thread locking and atomicity - If variables are only read/written within the same exclusive lock, it means that we isolate these variables to a specific thread, outside threads (concurrent processes) can't alter these variables - these variables are read/written atomically.
Additional reading:
C# Threading: Mutual exclusion (via Mutex Class)
http://msdn.microsoft.com/en-us/library/c5kehkcz(VS.71).aspx
http://msdn.microsoft.com/en-us/library/aa664735(VS.71).aspx
Note: Additional overloads added to .net 4.0
http://msdn.microsoft.com/en-us/library/system.threading.monitor.tryenter.aspx
Threading Guidelines:
http://msdn.microsoft.com/en-us/library/f857xew0%28VS.71%29.aspx
Date - 2010-08-06 15:31:15
Comments - 0
Book Review: PHP 6 and MySQL 5 for Dynamic Web Sites
This book has actually been on my bookshelf for quite a while, I bought it
a few months before the promised release of PHP 6 in 2008 (which never happend).
Unfortunately I didn't realise at the time that the author made a typo when he gave the book its title, since the book
primarily focuses on functionality thats been around since PHP 4 - with some PHP 5
examples (e.g. mysqli extension).
PHP 6 is more like a side note in this book.
I can however imagine that it is quite difficult to write a book about a product that
strictly speaking doesn't actually exist - so I will cut the author some slack. (apparently
a lot, if not most of the suggested PHP 6 functionality are currently available within PHP 5.3)
Looking at the actual content, the table of contents reveals that this book
is intended for beginners - so don't expect finding any nuclear bomb blueprints in this book (incidently).
I personally feel that the structure of this book is a bit illogical, for example in Chapter 3 on page 89 - 91
the author crudely explains how to create what he calls a sticky form (persisting selected/entered data in a form).
In order to get a less mediocre understanding of forms, the reader needs to advance to Chapter 8 on page 243 - 248
where they learn about magic quotes (which potentially messed up their sticky form back in Chapter 3) and
SQL injection (which potentially messed up their database if they had one).
Another crucial part that relates to the sticky form only really gets discussed in Chapter 12 - form/data validation, html
encoding (which potentially breaks their page layout) etc.
In my opinion it would have been more logical to explain all of these concepts together - since they are pretty much
directly related to one another.
But then again thats my own preferences I guess, at least the book contains these concepts.
All in all I dont feel its a bad book (for a beginner) - definitely not what I expected or had in mind when I purchased it (I was expecting more of a PHP 6 primer) - don't judge a book by its title.
Additional Reading:
Have a look at the Errata if you're planning to buy this book,
there is quite a number of little mistakes.
Also be sure to visit the author's (Larry Ullman) website
www.dmcinsights.com
Date - 2010-08-04 21:48:58
Comments - 0
First 1 2 3 4 5 6 7 8 9 10 Last / 42 Pages (83 Entries)