views:

34

answers:

2

Is it possible to skip to the end of a process's allocated time-quantum? I have a program that works in parallel on a piece of shared memory, and then all of the processes need to wait for the others to finish and sync up before the next step. Each process will do a maximum of one iteration more than any other, so any timing differences are minimal.

microsleep almost works, but I'm pretty sure that even usleep(1) would take longer than I'd like (as of now I can do 5000 times through in about 1.5 seconds, so that would add around 20ms to a test).

Some kind of busy wait seems like a bad idea, though it's what I might end up going with.

What I would really like is something along the lines of

while(*everyoneDone != 0) {
    //give up rest of this time-quantum
}

It doesn't need to be realtime, it just needs to be fast. Any ideas?

Note that this will be run on a multiproc machine, because if there's only one core to work with, the existing single-threaded version is going to perform better.

+1  A: 

You don't state what OS you're working with, but if it's POSIX then sched_yield() might be what you're looking for.

Really though, you'd almost certainly be better off using a proper synchronisation primitive, like a semaphore.

caf
That's precisely what I was looking for, but I'm only really looking for it since I didn't know about pthread_barrier_t, which seems to be what I actually need. Oh, and I did have to use a semaphore in order to make synchronize access to the shared status int. It wasn't pretty.
zebediah49
+1  A: 

Don't do that, active waiting is almost always a bad idea in an application context. Use pthread_barrier_t, this is exactly the tool that is foreseen for your purpose.

Jens Gustedt
I know it's a bad idea; that's why I'm looking for an alternative solution. I just couldn't find this it appears, since it looks like precisely what I actually want.
zebediah49
yeah, no offense intended, with "don't do that" I target the other answer of doing a yield.
Jens Gustedt
Aye, I agree completely (that's why I put the second paragraph in my answer). It wasn't clear exactly what synchronisation primitive the OP needed (barriers implies that you know ahead of time which will be the last thread to complete).
caf