PageRenderTime 6ms CodeModel.GetById 1ms app.highlight 2ms RepoModel.GetById 1ms app.codeStats 0ms

/trunk/Examples/test-suite/director_thread.i

#
Swig | 102 lines | 86 code | 14 blank | 2 comment | 0 complexity | 3436dc0bce438f667b56b2399fc09fd6 MD5 | raw file
  1// This testcase was in the python subdirectory
  2
  3#if defined(SWIGPYTHON)
  4// Is "threads" really needed for Python? It seems to work without it.
  5%module(directors="1",threads="1") director_thread
  6#else
  7%module(directors="1") director_thread
  8#endif
  9
 10%{
 11#ifdef _WIN32
 12#include <windows.h>
 13#include <process.h>
 14#else
 15#include <pthread.h>
 16#include <signal.h>
 17#include <unistd.h>
 18#endif
 19
 20#include <iostream>
 21
 22class Foo;  
 23extern "C" {
 24#ifdef _WIN32
 25  unsigned int __stdcall working(void* t);
 26  unsigned int thread_id(0);
 27#else
 28  void* working(void* t);
 29  pthread_t thread;
 30#endif
 31  static int thread_terminate = 0;
 32  
 33}
 34%}
 35
 36%director Foo;
 37
 38%inline {
 39  static void MilliSecondSleep(int milliseconds) {
 40  %#ifdef _WIN32
 41    Sleep(milliseconds);
 42  %#else
 43    usleep(milliseconds*1000);
 44  %#endif
 45  }
 46
 47  class Foo {
 48  public:
 49    int val;
 50    
 51    Foo() : val(0) {
 52    }
 53    
 54    virtual ~Foo()  {
 55    }
 56
 57    void stop() {
 58      thread_terminate = 1;
 59    %#ifdef _WIN32
 60      /*TODO(bhy) what to do for win32? */
 61    %#else  
 62      pthread_join(thread, NULL);
 63    %#endif
 64    }
 65
 66    void run() {
 67%#ifdef _WIN32
 68      _beginthreadex(NULL,0,working,this,0,&thread_id);
 69%#else
 70      pthread_create(&thread,NULL,working,this);
 71%#endif
 72      MilliSecondSleep(500);
 73    }
 74    
 75    virtual void do_foo() {
 76      val += 1;
 77    }
 78  };
 79}
 80
 81%{
 82extern "C" {
 83#ifdef _WIN32
 84  unsigned int __stdcall working(void* t)
 85#else
 86  void* working(void* t)
 87#endif
 88  {
 89    Foo* f = static_cast<Foo*>(t);
 90    while ( ! thread_terminate ) {
 91      MilliSecondSleep(50);
 92      f->do_foo();
 93    }
 94#ifdef _WIN32
 95    /* TODO(bhy) what's the corresponding of pthread_exit in win32? */
 96#else
 97    pthread_exit(0);
 98#endif
 99    return 0;
100  }
101}
102%}