我的多线程代码有什么问题?

问题描述 投票:0回答:1

我正在阅读 Bruce Eckel 的书 “Thinking in C++”,vol. 2 在做第 11 章的练习 13 时,我遇到了一个问题。

练习 13:创建两个 Runnable 子类,其中一个子类具有启动并调用 wait() 的 run()。另一个类的 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";
}

它挂起并且不打印“消息”。我做错了什么?

c++ multithreading
1个回答
0
投票

您的程序以 main 函数结束,两个线程都被中断。将休眠添加到主函数的末尾。

© www.soinside.com 2019 - 2024. All rights reserved.