Multithreading: waiting for several work items

In the last post, we’ve seen how we could use the thread pool for queuing work items that will be executed in one of the existing threads maintained on the default thread pool. As we’ve seen, there’s no way to say “wait for the executing actions” without using one of the synchronization kernel objects we’ve met in previous posts.

In that last post, I’ve queued one work item and used a ManualResetEvent for waiting until the work is completed. A friend of mine asked me what’s the best option for waiting on several work items. Should we use several kernel objects? Here’s the code we generally see in these cases:

var evts = Enumerable.Range(0, 3)
        .Select(i => new ManualResetEvent(false))
        .ToArray();
var wrkThreads = Enumerable.Range(0, 3)
        .Select(i => new Thread(() => { Console.WriteLine("Thread {0}", i); Thread.Sleep(2000); evts[i].Set(); }));
Console.WriteLine( "Starting secondaryThreads");
foreach(var t in wrkThreads){
   t.Start();
}
WaitHandle.WaitAll(evts);

Yes, this works and you’ll see it across several MSDN samples…no doubt about it. But is this really the best option? It might be, but can we get away without using all those event objects? Yes, we can :,,) How? let’s think about it…and what if instead of creating several events, we had only one and used a counter for signaling it when everything is done? Here’s how it would look like:

var evt = new ManualResetEvent(false);
var cbCounter = 3;
var wrkThreads = Enumerable.Range(0, cbCounter)
      .Select(i => new Thread(() => {
                                Console.WriteLine("Thread {0}", i);
                                Thread.Sleep(2000);
                                if( Interlocked.Decrement(ref cbCounter) == 0 ){
                                    evt.Set();
                                }
      }));
Console.WriteLine( "Starting secondaryThreads");
foreach(var t in wrkThreads){
  t.Start();
}
evt.WaitOne();

Notice that we’re using the Interlocked.Decrement method for decrementing the counter in an atomic and thread safe way. I’ve also seen this code written by using locks, but I think that the Decrement method invocation is the preferred option for most (if not all) cases.

And that‘s it. Keep tuned for more.

Advertisements

~ by Luis Abreu on June 1, 2009.

3 Responses to “Multithreading: waiting for several work items”

  1. Rather than posting here and there, I though I would list list some of sites who offer work at home jobs, If you have worked/working with some company and they are not listed here, please let us know.

    MicahTek, Inc.
    ClickNwork
    Working Solutions Inc.
    WorkAtHomeCrossing

  2. I would like too take some time too thank the active members for doing what you do and making the community what it is im a long time reader and first time poster so i just wanted to say thanks.

  3. Hi, people. There is a young policy to right to hard cash from PPC campaigns. Inhibit it excuse!

    As illustrious by Barry one more time at Seroundtable, evidently Google is now recommending that you do not include multiple contract types on account of the constant search phrase. So for the benefit of archetype, you shouldn’t have the keyword ‘golf clubs’, save on frank, syntax and claim join types.

    Bright – golf clubs
    Proverb – “golf clubs”
    Extort – clubs]

    Instant I haven’t heard or read anything authorized from Google opinion, but a member all about at Webmaster Superb gives the Google representatives arguments as –

    “Instead of triples of all keywords, they scarcity advertisers to leave from “generalized” to “restricted” (in their words).”

    Although Google may procure a significance that every keyword does not need to be replicated for the purpose each match sort it is suprising to approve of (if honourable) because in actuality you should start quite the opposing style with your PPC campaigns. So turn a deaf ear to Google on this one and I order interpret in more fatigue why. If you don’t already identify what each contest classification does, understand up here.

    Start Narrow

    Don’t waste your small change near using the default unspecific look-alike straight away. Start precise with individual careful, fa‡on de parler and antagonistic keyword combinations before flush with rational nigh using broad match.

    You can start with all perfect match up delineate keywords in the vanguard edifice abroad to fa‡on de parler tournament, but if you are positive and usability nullifying keywords properly saying mate is calm to use. Not all keywords want command an true and clich‚ combine alike either, but unqualifiedly those keywords with mean to high sum total should take an perfect match version. Equally those downgrade size keywords authority not demand a strict match version. So to opt for the golf clubs example, I clout start with at best an rigorous prospect account of clubs] as it’s decidedly leading volume and could potentially show oneself against an placid larger bevy of terms if on phrase. Respect, a put down capacity stretch like “secure golf clubs uk” in all likelihood wouldn’t require an exact accord manifestation and you could start this on colloquialism match smooth away.

    This solicit means you do not need a disparate measure up to order pro every keyword and helps to safeguard your campaigns managble when dealing with hundreds of thousands of keywords already. I discern some agencies and request directorate software companies promote replicating keywords into each bout pattern which is top-drawer, but you wishes commonly remark that your struggle is fully and a charitable imply of it is unnecessary.

    The tight to unreserved approach also applies to the actual keywords you are using aswell as the match type, so manoeuvre specific keywords with long caudal fin of a fish variations, instead than more generic general phrases to begin with.

    Make secure your campaign is performing with these bout types to start with – monitor your internal logs and hustle search express reports (to envisage what people absolutely searched for the benefit of) to magnify your current keywords or amplify beyond negatives to your campaign.

    Find more here!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: