C++编程思想 第2卷 第11章 并发 终止任务 中断 被一个互斥锁阻塞

如果试图调用一个函数
而该函数的互斥锁已经被别的线程获得
那么这个调用该函数的任务就会被挂起
直到该互斥锁变成可获得时为止

//: C11:Interrupting2.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.
// Interrupting a thread blocked
// with a synchronization guard.
//{L} ZThread
#include <iostream>
#include "zthread/Thread.h"
#include "zthread/Mutex.h"
#include "zthread/Guard.h"
using namespace ZThread;
using namespace std;

class BlockedMutex {
  Mutex lock;
public:
  BlockedMutex() {
    lock.acquire();
  }
  void f() {
    Guard<Mutex> g(lock);
    // This will never be available
  }
};

class Blocked2 : public Runnable {
  BlockedMutex blocked;
public:
  void run() {
    try {
      cout << "Waiting for f() in BlockedMutex" << endl;
      blocked.f();
    } catch(Interrupted_Exception& e) {
      cerr << e.what() << endl;
      // Exit the task
    }
  }
};

int main(int argc, char* argv[]) {
  try {
    Thread t(new Blocked2);
    t.interrupt();
  } catch(Synchronization_Exception& e) {
    cerr << e.what() << endl;
  }
  getchar();
} ///:~

输出
ThreadQueue created
Reference thread created.
1 reference-thread added.
User thread created.
pollPendingThreads()
1 user-thread added.
Thread starting...
Waiting for f() in BlockedMutex
Thread interrupted
Thread joining...
Thread exiting...
insertPendingThread()
1 pending-thread added.
** You are destroying a mutex which was never released. **
Assertion failed: 0, file 地址省略muteximpl.h, line 110 //这里跳出异常对话框

ThreadQueue waiting on remaining threads...
Reference thread created.
1 reference-thread added.
pollUserThreads()
pollPendingThreads()

BlockedMutex类有一个构造函数
获得对象自己的互斥锁Mutex并且绝不释放它
如果试图调用f() 总会被阻塞
因此互斥锁Mutex不能被获得

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值