Skip to main content
GameDev.net gamedev.net
🔒 Locked

Thread synchronization, waiting for multiple jobs

Started by ingramb May 10, 2013 at 7:02 AM 3 replies 1.2k views
Original Post
ingramb
ingramb

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?

ingramb
ingramb

It's a multi platform codebase so that's not an option.

ApochPiQ
ApochPiQ
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.