• Main Page
  • Namespaces
  • Classes
  • Files
  • File List
  • File Members

thread.test.h

Go to the documentation of this file.
00001 /* -*- C++ -*- (c) 2007 Petr Rockai <me@mornfall.net>
00002                (c) 2007 Enrico Zini <enrico@enricozini.org> */
00003 
00004 #include <wibble/sys/mutex.h>
00005 #include <wibble/sys/thread.h>
00006 
00007 #include <wibble/test.h>
00008 
00009 using namespace std;
00010 using namespace wibble::sys;
00011 
00012 struct TestThread {
00013     
00014     // Test threads that just assigns a value to an int and exists
00015     class Thread1 : public Thread
00016     {
00017     protected:
00018         int& res;
00019         int val;
00020         
00021         void* main()
00022         {
00023             res = val;
00024             return (void*)val;
00025         }
00026     public:
00027         Thread1(int& res, int val) : res(res), val(val) {}
00028     };
00029     
00030     // Thread that continuously increments an int value
00031     class Thread2 : public Thread
00032     {
00033     protected:
00034         int& res;
00035         Mutex& mutex;
00036         bool done;
00037 
00038         void* main()
00039         {
00040             while (!done)
00041             {
00042                 MutexLock lock(mutex);
00043                 ++res;
00044             }
00045             return 0;
00046         }
00047 
00048     public:
00049         Thread2(int& res, Mutex& mutex) :
00050             res(res), mutex(mutex), done(false) {}
00051         void quit() { done = true; }
00052     };
00053 
00054     // Test that threads are executed
00055     Test execution() {
00056     int val = 0;
00057 
00058     Thread1 assigner(val, 42);
00059     assigner.start();
00060     assert_eq(assigner.join(), (void*)42);
00061     assert_eq(val, 42);
00062     }
00063 
00064     // Use mutexes to access shared memory
00065     Test sharedMemory() {
00066         int val = 0;
00067         Mutex mutex;
00068 
00069         Thread2 incrementer(val, mutex);
00070         incrementer.start();
00071 
00072         bool done = false;
00073         while (!done)
00074         {
00075             MutexLock lock(mutex);
00076             if (val > 100)
00077         done = true;
00078         }
00079         incrementer.quit();
00080         assert_eq(incrementer.join(), (void*)0);
00081     }
00082 
00083 };
00084 
00085 // vim:set ts=4 sw=4:

Generated on Tue May 10 2011 16:51:50 for wibble by  doxygen 1.7.1