zthread中断和阻塞

1. 中断代码如下:

#include <iostream> #include "zthread/Thread.h" using namespace ZThread; using namespace std; class Blocked : public Runnable { public: void run() { try { Thread::sleep(1000); cout << "Waiting for get() in run():"; cin.get(); } catch(Interrupted_Exception&) { cout << "Caught Interrupted_Exception" << endl; // Exit the task } } }; int main(int argc, char* argv[]) { try { Thread t(new Blocked); if(argc > 1) Thread::sleep(1100); t.interrupt(); } catch(Synchronization_Exception& e) { cerr << e.what() << endl; } } ///:~

 

2.互斥锁的阻塞

#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; } } ///:~

 

这个例子说明 如果有2个线程  当其中一个调用另外一个正在访问的函数的时候,那么该线程就不能访问函数只能等待对象函数的锁变为可获得时访问。

在上面的情况中 由于Guard<Mutex> g(lock)  不会释放 所以弹出一个异常

 

 

关于中断状态

通过interrupt来设置中断状态 通过interrupted来检查中断状态

如下所示

#include <stdlib.h> #include <iostream> #include <zthread/thread.h> #pragma comment(lib,"ZThread_Z.lib") const double PI = 3.14159265358979323846; const double E = 2.7182818284590452354; using namespace std; using namespace ZThread; class NeedsCleanup { int id; public: NeedsCleanup(int ident) : id(ident) { cout << "NeedsCleanup " << id << endl; } ~NeedsCleanup() { cout << "~NeedsCleanup " << id << endl; } }; class Blocked3 : public Runnable { volatile double d; public: Blocked3() : d(0.0) {} void run() { try { while(!Thread::interrupted()) { point1: NeedsCleanup n1(1); cout << "Sleeping" << endl; Thread::sleep(1000); point2: NeedsCleanup n2(2); cout << "Calculating" << endl; // A time-consuming, non-blocking operation: for(int i = 1; i < 100000; i++) d = d + (PI + E) / (double)i; } cout << "Exiting via while() test" << endl; } catch(Interrupted_Exception&) { cout << "Exiting via Interrupted_Exception" << endl; } } }; int main(int argc, char* argv[]) { if(argc != 2) { cerr << "usage: " << argv[0] << " delay-in-milliseconds" << endl; exit(1); } int delay = atoi(argv[1]); try { Thread t(new Blocked3); Thread::sleep(delay); t.interrupt(); } catch(Synchronization_Exception& e) { cerr << e.what() << endl; } } ///:~

 

你可能感兴趣的:(thread,exception,Class,n2,delay)