Hi all,

I'm looking for a function that releases the CPU for the current executing thread. What I'm doing is implementing a multi-threaded approach to sum table calculations, and using OpenMP for multithreading. Here's the problem:

I have a thread that depends on a number of other threads to finish their calculations (which they'll set a flag). Until then, it just busy-waits polling for the flag. Here's the code snippet for that part (the entire code is a few hundred lines and I'd rather not post that):

while (avail[l1/inc1+1][l2/inc2] == 0
        || avail[l1/inc1][l2/inc2+1] == 0) 
	{
//	printf("Waiting for avail[%d][%d] and [%d][%d]\n", l1/inc1+1,l2/inc2, l1/inc1, l2/inc2+1);
	}

The problem is that when the printf is commented out, the program gets stuck infinite-loop-like behaviour. This infinite loop is not observed when debugged with GDB nor when the printf is uncommented, which makes identifying the problem rather difficult. I'm guessing that it's because the loop is refusing to give up CPU, and by putting a printf it gives up the CPU while waiting for the I/O call to complete, although I don't even see the printf being called sometimes (it seems random depending on which thread the CPU decides to execute first).
Which is the reason why I'm looking for a function call or macro or anything that just releases the CPU for the current thread.
sleep() is too long, I don't want to wait a full millisecond.

environment: Fedora 10, intel cpu

Thanks

Recommended Answers

All 3 Replies

MS-Windows: Sleep(int milliseconds)

*nix: sleep(int seconds) There is another one too that takes milliseconds but I don't recall its name.

In MS-Windows you can call WiatForMultipleObjects() to put the main thread to sleep until all worker threads have finished. You don't need that loop at all.

Thanks for the reply.

Like I said in my original post, sleep() is too long, I don't want to wait a full millisecond. The time I spend sleeping is probably longer than the time I save by multithreading this calculation.
Also, this is a recursive thread-spawning implementation, so the threads that its waiting for does not necessarily finish execution, it just finished that particular part of calculation.

The subject of this thread is "function to release cpu". Sleep, or a variant, does that. And the cpu can not be release for less than 1 millisecond, and in *nix there is no guarentee that it will be released that length of time.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.