Search code examples
c++multithreading

What is wrong with my multithreading code?


I am reading "Thinking in C++", vol. 2 by Bruce Eckel. I have encountered a problem while doing exercise 13 from chapter 11.

Exercise 13: Create two Runnable subclasses, one with a run() that starts and calls wait(). The other class’s run() should capture the reference of the first Runnable object. Its run() should call signal() for the first thread after some number of seconds have passed so that first thread can print a message.

Runnable class is from the ZThreads library.

Here is my code:

#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";
}

The program freezes and doesn't print "Message". What am I doing wrong?


Solution

  • Your program ends with function main and both threads are interrupted. Add sleeping to the end of the main function.