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

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

      executor.execute(new LiftOff(10, i));

  } catch(Synchronization_Exception& e) {

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

  }

} ///:~

Like a ConcurrentExecutor, a SynchronousExecutor is used when you want only one task at a time to run, serially instead of concurrently. Unlike ConcurrentExecutor, a SynchronousExecutor doesn’t create or manage threads on it own. It uses the thread that submits the task and thus only acts as a focal point for synchronization. If you have n threads submitting tasks to a SynchronousExecutor, those threads are all blocked on execute( ). One by one they will be allowed to continue as the previous tasks in the queue complete, but no two tasks are ever run at once.

For example, suppose you have a number of threads running tasks that use the file system, but you are writing portable code so you don’t want to use flock( ) or another OS-specific call to lock a file. You can run these tasks with a SynchronousExecutor to ensure that only one task at a time is running from any thread. This way, you don’t have to deal with synchronizing on the shared resource (and you won’t clobber the file system in the meantime). A better solution is to actually synchronize on the resource (which you’ll learn about later in this chapter), but a SynchronousExecutor lets you skip the trouble of getting coordinated properly just to prototype something.

//: C11:SynchronousExecutor.cpp

//{L} ZThread

#include "zthread/SynchronousExecutor.h"

#include "LiftOff.h"

using namespace ZThread;

using namespace std;

int main() {

  try {

    SynchronousExecutor executor;

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

      executor.execute(new LiftOff(10, i));

  } catch(Synchronization_Exception& e) {

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

  }

} ///:~

When you run the program, you’ll see that the tasks are executed in the order they are submitted, and each task runs to completion before the next one starts. What you don’t see is that no new threads are created—the main( ) thread is used for each task, since in this example, that’s the thread that submits all the tasks. Because SynchronousExecutor is primarily for prototyping, you may not use it much in production code.

Yielding

If you know that you’ve accomplished what you need to during one pass through a loop in your run( ) function (most run( ) functions involve a long-running loop), you can give a hint to the thread scheduling mechanism that you’ve done enough and that some other thread might as well have the CPU. This hint (and it is a hint—there’s no guarantee your implementation will listen to it) takes the form of the yield( ) function.

We can make a modified version of the LiftOff examples by yielding after each loop:

//: C11:YieldingTask.cpp

// Suggesting when to switch threads with yield().

//{L} ZThread

#include <iostream>

#include "zthread/Thread.h"

#include "zthread/ThreadedExecutor.h"

using namespace ZThread;

using namespace std;

class YieldingTask : public Runnable {

  int countDown;

  int id;

public:

  YieldingTask(int ident = 0) : countDown(5), id(ident) {}

  ~YieldingTask() {

    cout << id << " completed" << endl;

  }

  friend ostream&

  operator<<(ostream& os, const YieldingTask& yt) {

    return os << "#" << yt.id << ": " << yt.countDown;

  }

  void run() {

    while(true) {

      cout << *this << endl;

      if(--countDown == 0) return;

      Thread::yield();

    }

  }

};

int main() {

  try {

    ThreadedExecutor executor;

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

      executor.execute(new YieldingTask(i));

  } catch(Synchronization_Exception& e) {

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

  }

} ///:~

You can see that the task’s run( ) member function consists entirely of an infinite loop. By using yield( ), the output is evened up quite a bit over that without yielding. Try commenting out the call to Thread::yield( ) to see the difference. In general, however, yield( ) is useful only in rare situations, and you can’t rely on it to do any serious tuning of your application.

Sleeping

Another way you can control the behavior of your threads is by calling sleep( ) to cease execution of that thread for a given number of milliseconds. In the preceding example, if you replace the call to yield( ) with a call to sleep( ), you get the following:

//: C11:SleepingTask.cpp

// Calling sleep() to pause for awhile.

//{L} ZThread

#include <iostream>

#include "zthread/Thread.h"

#include "zthread/ThreadedExecutor.h"

using namespace ZThread;

using namespace std;

class SleepingTask : public Runnable {

  int countDown;

  int id;

public:

  SleepingTask(int ident = 0) : countDown(5), id(ident) {}

  ~SleepingTask() {

    cout << id << " completed" << endl;

  }

  friend ostream&

  operator<<(ostream& os, const SleepingTask& st) {

    return os << "#" << st.id << ": " << st.countDown;

  }

  void run() {

    while(true) {

      try {

        cout << *this << endl;

        if(--countDown == 0) return;

        Thread::sleep(100);

      } catch(Interrupted_Exception& e) {

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

      }

    }

  }

};

int main() {

  try {

    ThreadedExecutor executor;

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

      executor.execute(new SleepingTask(i));

  } catch(Synchronization_Exception& e) {

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

  }

} ///:~

Thread::sleep( ) can throw an Interrupted_Exception (you’ll learn about interrupts later), and you can see that this is caught in run( ). But the task is created and executed inside a try block in main( ) that catches Synchronization_Exception (the base class for all ZThread exceptions), so wouldn’t it be possible to just ignore the exception in run( ) and assume that it will propagate to the handler in main( )? This won’t work because exceptions won’t propagate across threads back to main( ). Thus, you must handle any exceptions locally that may arise within a task.