Выбрать главу

#include <iostream>

class Generator : public ZThread::Cancelable {

  bool canceled;

public:

  Generator() : canceled(false) {}

  virtual int nextValue() = 0;

  void cancel() { canceled = true; }

  bool isCanceled() { return canceled; }

};

class EvenChecker : public ZThread::Runnable {

  ZThread::CountedPtr<Generator> generator;

  int id;

public:

  EvenChecker(ZThread::CountedPtr<Generator>& g, int ident)

  : generator(g), id(ident) {}

  ~EvenChecker() {

    std::cout << "~EvenChecker " << id << std::endl;

  }

  void run() {

    while(!generator->isCanceled()) {

      int val = generator->nextValue();

      if(val % 2 != 0) {

        std::cout << val << " not even!" << std::endl;

        generator->cancel(); // Cancels all EvenCheckers

      }

    }

  }

  // Test any type of generator:

  template<typename GenType> static void test(int n = 10) {

    std::cout << "Press Control-C to exit" << std::endl;

    try {

      ZThread::ThreadedExecutor executor;

      ZThread::CountedPtr<Generator> gp(new GenType);

      for(int i = 0; i < n; i++)

        executor.execute(new EvenChecker(gp, i));

    } catch(ZThread::Synchronization_Exception& e) {

      std::cerr << e.what() << std::endl;

    }

  }

};

#endif // EVENCHECKER_H ///:~

The Generator class introduces the pure abstract Cancelable class, which is part of the ZThread library. The goal of Cancelable is to provide a consistent interface to change the state of an object via the cancel( ) function and to see whether the object has been canceled with the isCanceled( ) function. Here, the simple approach of a bool canceled flag is used, similar to the quitFlag previously seen in ResponsiveUI.cpp. Note that in this example the class that is Cancelable is not Runnable. Instead, all the EvenChecker tasks that depend on the Cancelable object (the Generator) test it to see if it’s been canceled, as you can see in run( ). This way, the tasks that share the common resource (the Cancelable Generator) watch that resource for the signal to terminate. This eliminates the so-called race condition, in which two or more tasks race to respond to a condition and thus collide or otherwise produce inconsistent results. You must be careful to think about and protect against all the possible ways a concurrent system can fail. For example, a task cannot depend on another task, because there’s no guarantee of the order in which tasks will be shut down. Here, by making tasks depend on non-task objects, we eliminate the potential race condition.

In later sections, you’ll see that the ZThread library contains more general mechanisms for termination of threads.

Since multiple EvenChecker objects may end up sharing a Generator, the CountedPtr template is used to reference count the Generator objects.

The last member function in EvenChecker is a static member template that sets up and performs a test of any type of Generator by creating one inside a CountedPtr and then starting a number of EvenCheckers that use that Generator. If the Generator causes a failure, test( ) will report it and return; otherwise, you must press Control-C to terminate it.

EvenChecker tasks constantly read and test the values from their associated Generator. Note that if generator->isCanceled( ) is true, run( ) returns, which tells the Executor in EvenChecker::test( ) that the task is complete. Any EvenChecker task can call cancel( ) on its associated Generator, which will cause all other EvenCheckers using that Generator to gracefully shut down.

The EvenGenerator is simple –nextValue( ) produces the next even value:

//: C11:EvenGenerator.cpp

// When threads collide.

//{L} ZThread

#include "EvenChecker.h"

#include "zthread/ThreadedExecutor.h"

#include <iostream>

using namespace ZThread;

using namespace std;

class EvenGenerator : public Generator {

  int currentEvenValue;

public:

  EvenGenerator() { currentEvenValue = 0; }

  ~EvenGenerator() { cout << "~EvenGenerator" << endl; }

  int nextValue() {

    currentEvenValue++; // Danger point here!

    currentEvenValue++;

    return currentEvenValue;

  }

};

int main() {

  EvenChecker::test<EvenGenerator>();

} ///:~

It’s possible for one thread to call nextValue( ) after the first increment of currentEvenValue and before the second (at the place in the code commented "Danger point here!"), in which case the value would be in an "incorrect" state. To prove that this can happen, EvenChecker::test( ) creates a group of EvenChecker objects to continually read the output of an EvenGenerator and test to see if each one is even. If not, the error is reported and the program is shut down.

This program may not detect the problem until the EvenGenerator has completed many cycles, depending on the particulars of your operating system and other implementation details. If you want to see it fail much faster, try putting a call to yield( ) between the first and second increments. In any event, it will eventually fail because the EvenChecker threads are able to access the information in EvenGenerator while it’s in an "incorrect" state.

Controlling access

The previous example shows a fundamental problem when using threads: You never know when a thread might be run. Imagine sitting at a table with a fork, about to spear the last piece of food on your plate, and as your fork reaches for it, the food suddenly vanishes (because your thread was suspended and another task came in and stole the food). That’s the problem you’re dealing with when writing concurrent programs.

Sometimes you don’t care if a resource is being accessed at the same time you’re trying to use it (the food is on some other plate). But for multithreading to work, you need some way to prevent two threads from accessing the same resource, at least during critical periods.

Preventing this kind of collision is simply a matter of putting a lock on a resource when one thread is using it. The first thread that accesses a resource locks it, and then the other threads cannot access that resource until it is unlocked, at which time another thread locks and uses it, and so on. If the front seat of the car is the limited resource, the child who shouts "Dibs!" acquires the lock.