| 1 |
/*********************************************************************** |
| 2 |
* Code listing from "Advanced Linux Programming," by CodeSourcery LLC * |
| 3 |
* Copyright (C) 2001 by New Riders Publishing * |
| 4 |
* See COPYRIGHT for license information. * |
| 5 |
***********************************************************************/ |
| 6 |
|
| 7 |
#include <pthread.h> |
| 8 |
|
| 9 |
extern bool should_exit_thread_immediately (); |
| 10 |
|
| 11 |
class ThreadExitException |
| 12 |
{ |
| 13 |
public: |
| 14 |
/* Create an exception signalling thread exit with RETURN_VALUE. */ |
| 15 |
ThreadExitException (void* return_value) |
| 16 |
: thread_return_value_ (return_value) |
| 17 |
{ |
| 18 |
} |
| 19 |
|
| 20 |
/* Actually exit the thread, using the return value provided in the |
| 21 |
constructor. */ |
| 22 |
void* DoThreadExit () |
| 23 |
{ |
| 24 |
pthread_exit (thread_return_value_); |
| 25 |
} |
| 26 |
|
| 27 |
private: |
| 28 |
/* The return value that will be used when exiting the thread. */ |
| 29 |
void* thread_return_value_; |
| 30 |
}; |
| 31 |
|
| 32 |
void do_some_work () |
| 33 |
{ |
| 34 |
while (1) { |
| 35 |
/* Do some useful things here... */ |
| 36 |
|
| 37 |
if (should_exit_thread_immediately ()) |
| 38 |
throw ThreadExitException (/* thread's return value = */ NULL); |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
void* thread_function (void*) |
| 43 |
{ |
| 44 |
try { |
| 45 |
do_some_work (); |
| 46 |
} |
| 47 |
catch (ThreadExitException ex) { |
| 48 |
/* Some function indicated that we should exit the thread. */ |
| 49 |
ex.DoThreadExit (); |
| 50 |
} |
| 51 |
return NULL; |
| 52 |
} |