when_exit.cc

Example # 8 - Exit.
This is a test of the special shutdown that occurs when all threads, including the main one, call threadmm::thread::exit().
This example demonstrates that atexit handlers are properly called, and that the output is properly flushed even when stdout is redirected to a file, and therefore fully buffered.

//
// $Id: when_exit.cc,v 1.5 2003/10/30 15:05:12 cholm Exp $ 
//  
//  Test of threads - C example ex7.c
//  Copyright (C) 2002 Christian Holm Christensen <cholm@nbi.dk> 
//
//  This library is free software; you can redistribute it and/or 
//  modify it under the terms of the GNU Lesser General Public License 
//  as published by the Free Software Foundation; either version 2.1 
//  of the License, or (at your option) any later version. 
//
//  This library is distributed in the hope that it will be useful, 
//  but WITHOUT ANY WARRANTY; without even the implied warranty of 
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
//  Lesser General Public License for more details. 
// 
//  You should have received a copy of the GNU Lesser General Public 
//  License along with this library; if not, write to the Free 
//  Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 
//  02111-1307 USA 
//
#ifndef OPTION_HH
#include "option.hh"
#endif
#ifndef THREADMM_thread
#include <threadmm/thread.hh>
#endif
#ifndef THREADMM_thread_group
#include <threadmm/thread_group.hh>
#endif
#ifndef __CSTDLIB__
#include <cstdlib>
#endif


using namespace std;

static void my_atexit(void) 
{
  cout << "in `atexit' handler" << endl;
}


namespace example 
{
  
  class print : public threadmm::thread
  {
  private: 
    int _i;
  public:
    print(int i) : _i(i) {}
    void* operator()()  { 
      cout << "Thread "<< _i << " terminating" << endl;
      return 0; 
    }
  };

  class when_exit 
  {
  private:
    
  public:
    when_exit() {}
    int run() { 
      try {
  atexit(my_atexit);
  
  threadmm::thread_group group;
  for (int i = 0; i < 20; i++) {
    std::cout << "Hello, starting thread # "<< i << std::endl;
    threadmm::thread* p = new print(i);
    group.add(p);
    p->run();
  }
  group.join();
  return 0;
      }
      catch(exception& e) {
  cerr << e.what() << endl;
      }
      std::cout << "Never reached" << std::endl;
      return 0; 
    }
  };
}

//_______________________________________________________________________
int main(int argc, char** argv)
{
  if (!example::options(argc, argv)) return 0;

  example::when_exit exa;
  return exa.run();
}

//_______________________________________________________________________
// 
// EOF
//



Top of page
Last update Tue Nov 9 12:40:50 2004
Christian Holm
Created by DoxyGen 1.3.9.1