我正在读Bruce Eckel的书"Thinking in C++", vol. 2,而在第11章练习13时我遇到了一个问题。
练习13:创建两个Runnable子类,一个带有run(),启动并调用wait()。另一个类的run()应该捕获第一个Runnable对象的引用。它的run()应该在经过一些秒后调用第一个线程的signal(),这样第一个线程就可以打印一条消息。
Runnable类来自ZThreads库。
这是我的代码:
#include <iostream>
#include "zthread/Runnable.h"
#include "zthread/Condition.h"
#include "zthread/Mutex.h"
#include "zthread/Guard.h"
#include "zthread/CountedPtr.h"
#include "zthread/Thread.h"
class Class1: public ZThread::Runnable {
ZThread::Mutex lock;
ZThread::Condition condition;
public:
Class1(): condition(lock) {}
void run() {
ZThread::Guard<ZThread::Mutex> g(lock);
std::cout << "Class1::run()\n";
condition.wait();
std::cout << "Message\n";
}
void continue1() {
ZThread::Guard<ZThread::Mutex> g(lock);
std::cout << "Class1::continue1()\n";
condition.signal();
}
};
class Class2: public ZThread::Runnable {
ZThread::CountedPtr<Class1>& c;
public:
Class2(ZThread::CountedPtr<Class1>& c1): c(c1) {}
void run() {
std::cout << "Class2::run()\n";
ZThread::Thread::sleep(2000);
std::cout << "Calling continue1()\n";
c->continue1();
std::cout << "Exiting Class2::run()\n";
}
};
int main() {
ZThread::CountedPtr<Class1> c(new Class1);
std::cout << "Starting thread 1\n";
ZThread::Thread t1(c);
std::cout << "Starting thread 2\n";
ZThread::Thread t2(new Class2(c));
std::cout << "exit\n";
}
它挂起并且不打印“消息”。我做错了什么?
答案 0 :(得分:0)
您的程序以函数main结束,两个线程都被中断。将sleep添加到main函数的末尾。