Multithreading: Coordinating multiple steps

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Multithreading: Coordinating multiple steps

Postby Berengal » Fri May 16, 2008 5:01 am UTC

Okay, so this is in Java, but I figure it applies to threads of all kinds:

I have multiple objects which I do calculations upon concurrently. They all share a common state object they need to consult and update in turn, but all objects need to be done with their calculations before they can update. In pseudocode:
  1. Get state
  2. Calculate difference to next state
  3. Wait for all threads to finish calculation (I'm thinking "commonObject.wait()")
  4. Update state ("commonObject.state += state" sort of thing. It doesn't matter in what order the threads update the state)
I'll need something to keep track of the threads, to know when they're all finished and can move on to the next phase. This is where I'm stumped. I'm thinking a counter of unfinished threads, like this:

Code: Select all

// calculations
synchronized (commonObject) {
  commonObject.runningThreads -= 1;
  if (commonObject.runningThreads == 0) commonObject.notifyAll();
  else commonObject.wait();
  commonObject.runningThreads += 1;
}
// updates

But I'm not sure if that's the best way.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

Karrion
Posts: 92
Joined: Fri Jun 22, 2007 12:14 am UTC
Location: Melbourne, AU

Re: Multithreading: Coordinating multiple steps

Postby Karrion » Fri May 16, 2008 6:49 am UTC

Berengal wrote:I'll need something to keep track of the threads, to know when they're all finished and can move on to the next phase.


Sounds like you want a Barrier

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Multithreading: Coordinating multiple steps

Postby Berengal » Fri May 16, 2008 9:15 am UTC

Why yes, it does. Thank you.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 9 guests