如果试图调用一个函数
而该函数的互斥锁已经被别的线程获得
那么这个调用该函数的任务就会被挂起
直到该互斥锁变成可获得时为止
//: 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不能被获得