Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




Thinking in C++ Vol 2 - Practical Programming
Prev Home Next


If you know that you ve accomplished what you need to during one pass through a loop in your run( ) function (most run( ) functions involve a long-running loop), you can give a hint to the thread scheduling mechanism that you ve done enough and that some other thread might as well have the CPU. This hint (and it is a hint there s no guarantee your implementation will listen to it) takes the form of the yield( ) function.

We can make a modified version of the LiftOff examples by yielding after each loop:

//: C11:YieldingTask.cpp
// Suggesting when to switch threads with yield().
//{L} ZThread
#include <iostream>
#include "zthread/Thread.h"
#include "zthread/ThreadedExecutor.h"
using namespace ZThread;
using namespace std;
class YieldingTask : public Runnable {
int countDown;
int id;
YieldingTask(int ident = 0) : countDown(5), id(ident) {}
~YieldingTask() {
cout << id << " completed" << endl;
friend ostream&
operator<<(ostream& os, const YieldingTask& yt) {
return os << "#" << << ": " << yt.countDown;
void run() {
while(true) {
cout << *this << endl;
if(--countDown == 0) return;
int main() {
try {
ThreadedExecutor executor;
for(int i = 0; i < 5; i++)
executor.execute(new YieldingTask(i));
} catch(Synchronization_Exception& e) {
cerr << e.what() << endl;
} ///:~

You can see that the task s run( ) member function consists entirely of an infinite loop. By using yield( ), the output is evened up quite a bit over that without yielding. Try commenting out the call to Thread::yield( ) to see the difference. In general, however, yield( ) is useful only in rare situations, and you can t rely on it to do any serious tuning of your application.

Thinking in C++ Vol 2 - Practical Programming
Prev Home Next

   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire