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.
//: 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;
public:
YieldingTask(int ident = 0) : countDown(5), id(ident)
{}
~YieldingTask() {
cout << id << " completed"
<< endl;
}
friend ostream&
operator<<(ostream& os, const
YieldingTask& yt) {
return os << "#" << yt.id
<< ": " << yt.countDown;
}
void run() {
while(true) {
cout << *this << endl;
if(--countDown == 0) return;
Thread::yield();
}
}
};
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;
}
} ///:~