如果知道run()函数的一次遍历循环期间已经完成了所需要的工作
可以给线程调度机制一个暗示
现在已经做完该做的工作
可以让其他线程使用CPU
每次循环后使用让步操作
可以产生一个LiftOff
//: C11:YieldingTask.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// 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;
}
getchar();
} ///:~
输出
ThreadQueue created
User thread created.
Reference thread created.
1 reference-thread added.
pollPendingThreads()
1 user-thread added.
Thread starting...
User thread created.
#0: pollPendingThreads()
5
1 user-thread added.
#0: User thread created.
4
Thread starting...
#0pollPendingThreads()
: 3#
1 user-thread added.
1Thread starting...
User thread created.
#: 25:
5#
0: 2
#1#: 42
pollPendingThreads()
: 1 user-thread added.
4Thread starting...
User thread created.
#
3: 5#
#10: : 13
Thread joining...
Thread exiting...
pollPendingThreads()
1 user-thread added.
#3insertPendingThread()
#1#: Thread starting...
2: 1 pending-thread added.
3
: 4#
4: 52#
2: 2
#30:
3
#4: 4
completed
#1#: #14
: 3
#3: Thread joining...
2
2: Thread exiting...
1
#4insertPendingThread()
: #3: Thread joining...
1 pending-thread added.
2
1
Thread exiting...
insertPendingThread()
Thread joining...
1 completed
#4Thread exiting...
: 1
1 pending-thread added.
insertPendingThread()
1 pending-thread added.
2 completed
3 completed
Thread joining...
Thread exiting...
insertPendingThread()
1 pending-thread added.
4 completed
任务run()成员函数完全由一个无限循环组成
使用yield()比不使用它
程序的输出均衡许多