Jump to content
  • Advertisement
Sign in to follow this  
ingramb

Thread synchronization, waiting for multiple jobs

This topic is 1866 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I often find myself writing code where I want to kick off a bunch of jobs, and then wait for them all to complete.  I've come up with something like this:

 

int pendingJobCount = 0;
Event jobsComplete( true );

void AddJob()
{
	int newCount = InterlockedIncrement( pendingJobCount );
	if( newCount == 1 )
	{
		jobsComplete.Reset();
	}
}

void FinishJob()
{
	int newCount = InterlockedDecrement( pendingJobCount );
	if( newCount == 0 )
	{
		jobsComplete.Signal();
	}
}

AddJob();
AddJob();
AddJob();
...
jobsComplete.Wait();
Assert( pendingJobCount == 0 ); 

This seems to work, but I'm curious if this is a standard way of doing things, or if there's a better technique.  Is there a more traditional synchronization primitive that will accomplish this?

Share this post


Link to post
Share on other sites
Advertisement
There are some race conditions in this code.

One example:
  • Thread 1 enters FinishJob() and decrements count to 0
  • Thread 1 is suspended after the if() check but before the event is signaled
  • Thread 2 enters and queues a job
  • Thread 2 suspends and Thread 1 resumes
  • Thread 1 signals the event but there are still jobs in flight due to Thread 2
Whether or not this adversely affects your use cases is hard to ascertain without further details, but it's something to be aware of.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!