00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023 #include "Basics.H"
00024
00025 using std::cout;
00026 using std::endl;
00027
00028 const int Arg1 = 4;
00029 const int Res1 = 5;
00030 const int PauseSecs = 1;
00031 const int MainPause = 4;
00032 const int SubPause = 2;
00033
00034 Basics::mutex mu;
00035
00036 void* Thread1(void *arg)
00037 {
00038 mu.lock();
00039 cout << " Starting Thread1...\n";
00040
00041 int val = *(int *)arg;
00042 assert(val == Arg1);
00043 cout << " Got arg " << val << " okay.\n";
00044 delete (int *)arg;
00045
00046 cout << " Producing result " << Res1 << ".\n";
00047 int *res = NEW(int);
00048 *res = Res1;
00049
00050 cout << " Done Thread1.\n";
00051 mu.unlock();
00052 return res;
00053 }
00054
00055 void *Thread2(void *arg)
00056 {
00057 mu.lock();
00058 cout << " Starting Thread2...\n";
00059 (cout << " Pausing " << PauseSecs << " second(s)...\n").flush();
00060 Basics::thread::pause(PauseSecs);
00061 (cout << " Done Thread2.\n").flush();
00062 mu.unlock();
00063 return (void *)NULL;
00064 }
00065
00066 void *Thread3(void *arg)
00067 {
00068 mu.lock();
00069 cout << " Starting Thread2...\n";
00070 (cout << " Pausing " << SubPause << " second(s)...\n").flush();
00071 mu.unlock();
00072 Basics::thread::pause(SubPause);
00073 mu.lock();
00074 (cout << " Done Thread2.\n").flush();
00075 mu.unlock();
00076 return (void *)NULL;
00077 }
00078
00079 int main(void)
00080 {
00081 mu.lock();
00082 cout << "Starting main thread...\n\n";
00083
00084 cout << "Forking Thread1(" << Arg1 << ")...\n";
00085 Basics::thread th;
00086 int *arg1 = NEW(int); *arg1 = Arg1;
00087 th.fork(Thread1, arg1);
00088 cout << "Joining Thread1...\n";
00089 mu.unlock();
00090 int *res = (int *)(th.join());
00091 assert(*res == Res1);
00092 mu.lock();
00093 cout << "Got result " << *res << " okay.\n\n";
00094 delete res;
00095
00096 cout << "Forking Thread2...\n";
00097 th.fork(Thread2, (void *)NULL);
00098 cout << "Joining Thread2...\n";
00099 mu.unlock();
00100 res = (int *)(th.join());
00101 assert(res == (void *)NULL);
00102 mu.lock();
00103 cout << "Joined okay.\n\n";
00104
00105 cout << "Forking and detaching Thread3...\n";
00106 mu.unlock();
00107 th.fork_and_detach(Thread3, (void *)NULL);
00108 mu.lock();
00109 (cout << "Main thread pausing " << MainPause << " second(s)...\n").flush();
00110 mu.unlock();
00111 Basics::thread::pause(MainPause);
00112 mu.lock();
00113 (cout << "Paused okay.\n\n").flush();
00114
00115 cout << "Done main thread." << endl;
00116 mu.unlock();
00117
00118 return 0;
00119 }