C++编程思想 第2卷 第11章 并发 使用线程 让步

如果知道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()比不使用它
程序的输出均衡许多

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值