473,387 Members | 1,549 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

synchronizations of threads

The following example of rudimentary thread pool is 'bluntly' copied
from "Accelerated C#" book. My questions follow the code:

using System;
using System.Threading;
using System.Collections;
public class CrudeThreadPool
{
static readonly int MAX_WORK_THREADS = 4;
static readonly int WAIT_TIMEOUT = 2000;
public delegate void WorkDelegate();

public CrudeThreadPool() {
stop = 0;
workLock = new Object();
workQueue = new Queue();
threads = new Thread[ MAX_WORK_THREADS ];
for( int i = 0; i < MAX_WORK_THREADS; ++i ) {
threads[i] =new Thread( new
ThreadStart(this.ThreadFunc) );
threads[i].Start();
}
}
private void ThreadFunc() {
lock( workLock ) {
int shouldStop = 0;
do {
shouldStop = Interlocked.Exchange( ref stop,stop );
if( shouldStop == 0 )
{
WorkDelegate workItem = null;
if( Monitor.Wait(workLock, WAIT_TIMEOUT) ) {
// Process the item on the front of the
queue
lock( workQueue ) {
workItem =(WorkDelegate)
workQueue.Dequeue();
}
workItem();
}
}
} while( shouldStop == 0 );
}
}
public void SubmitWorkItem( WorkDelegate item ) {
lock( workLock ) {
lock( workQueue ) {
workQueue.Enqueue( item );
}
Monitor.Pulse( workLock );
}
}
public void Shutdown() {
Interlocked.Exchange( ref stop, 1 );
}
private Queue workQueue;
private Object workLock;
private Thread[] threads;
private int stop;
}
public class EntryPoint
{
static void WorkFunction() {
Console.WriteLine( "WorkFunction() called on Thread {0}",
Thread.CurrentThread.GetHashCode() );
}
static void Main() {
CrudeThreadPool pool = new CrudeThreadPool();
for( int i = 0; i < 10; ++i ) {
pool.SubmitWorkItem(new
CrudeThreadPool.WorkDelegate(EntryPoint.WorkFuncti on) );
}
pool.Shutdown();
}
}

SO my question is why do we need need workLock, can we just use
workQueue to synchronize the access to the queue and manage the
execution of threads in the pool?
Thanks
Oct 19 '08 #1
2 1289
On Sun, 19 Oct 2008 14:48:35 -0700, puzzlecracker <ir*********@gmail.com>
wrote:
[...]
SO my question is why do we need need workLock, can we just use
workQueue to synchronize the access to the queue and manage the
execution of threads in the pool?
Is that really the code directly from the book, verbatim? What edition of
the book are you looking at?

To answer your immediate question, it's not the lock using workLock that's
superfluous, it's the lock using workQueue. In fact, IMHO the lock using
workQueue shouldn't be used at all. As has been discussed elsewhere,
including in Jon Skeet's web article on threading, using a privately
allocated instance of Object for a lock is preferable to using the object
that actually needs the synchronized access, because doing so ensures that
only that particular code is locking on that particular object.

At the very least, using a "public" reference (that is, a reference that
some other code might see, whether the variable itself is public or not)
runs the risk of increased contention, and it even slightly increases the
risk of having a deadlock bug.

In this particular context, I see no value at all in the inner lock. The
code is already synchronized with the other code in the example that
touches the object and that's sufficient.

Now, that said, that's not the only, or even most serious problem I see
with the code. I am surprised to see the non-generic Queue class being
used, but more significantly the use of the "stop" variable to signal a
shutdown rather than just communicating through the queue, which leads to
the two-second timeout, another questionable design choice, and the fact
that the workLock lock is held during the entire execution of the worker
delegate (imagine if the .NET ThreadPool class blocked any thread trying
to queue a work item until _all_ currently queued and executing tasks were
done), these are all bad problems IMHO.

In other words, I'm not sure I'd use this kind of code as a way to learn
about how best to implement threaded code. It has the scent of being
written by someone who knows just enough to be dangerous.

Interestingly, Jon reviewed this book and while he did have some
observations about the threading examples, he didn't have any particular
comments about that example. I don't know whether that's because Jon
thought the queue example was fine, or he just thought his point about the
weakness in Nash's presentation on threading was made well enough with the
example he did comment on, but if the former that might mean I've
overlooked something that justifies the implementation is it is. I don't
think I did, but you never know. :)

Pete
Oct 19 '08 #2
Is that really the code directly from the book, verbatim? *What editionof *
the book are you looking at?
Yes, copied exactly as stated written in the book (page 343)
To answer your immediate question, it's not the lock using workLock that's *
superfluous, it's the lock using workQueue. *In fact, IMHO the lock using *
workQueue shouldn't be used at all. *As has been discussed elsewhere, *
including in Jon Skeet's web article on threading, using a privately *
allocated instance of Object for a lock is preferable to using the object*
that actually needs the synchronized access, because doing so ensures that *
only that particular code is locking on that particular object.
That is a different issue, but I agree that a separate object (aka
lock) instance should be used for synchronization.

Oct 20 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Ronan Viernes | last post by:
Hi, I have created a python script (see below) to count the maximum number of threads per process (by starting new threads continuously until it breaks). ###### #testThread.py import...
0
by: Al Tobey | last post by:
I was building perl 5.8.2 on RedHat Enterprise Linux 3.0 (AS) today and noticed that it included in it's ccflags "-DTHREADS_HAVE_PIDS." I am building with -Dusethreads. With newer Linux...
6
by: m | last post by:
Hello, I have an application that processes thousands of files each day. The filenames and various related file information is retrieved, related filenames are associate and placed in a linked...
34
by: Kovan Akrei | last post by:
Hi, I would like to know how to reuse an object of a thread (if it is possible) in Csharp? I have the following program: using System; using System.Threading; using System.Collections; ...
7
by: Mr. Mountain | last post by:
In the following code I simulate work being done on different threads by sleeping a couple methods for about 40 ms. However, some of these methods that should finish in about 40 -80 ms take as long...
3
by: bygandhi | last post by:
Hi - I am writing a service which will check a process and its threads for their state ( alive or dead ). The process has 5 .net managed threads created using thread.start and each have been...
10
by: [Yosi] | last post by:
I would like to know how threads behavior in .NET . When an application create 4 threads for example start all of them, the OS task manager will execute all 4 thread in deterministic order manes,...
3
by: mjheitland | last post by:
Hi, I like to know how many threads are used by a Threading.Timer object. When I create a Threading.Timer object calling a short running method every 5 seconds I expected to have one additional...
10
by: Darian | last post by:
Is there a way to find all the thread names that are running in a project? For example, if I have 5 threads T1, T2, T3, T4, T5...and T2, T4, and T5 are running...I want to be able to know that...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.