ch4-cxx-exit

Chapter_4     cleanup job-queue1







cxx-exit.cpp     ALP, p. 75-76


#include <cstdio> // for printf()
#include <cstring> // for strcpy()
#include <malloc.h> // for malloc(), free()
#include <pthread.h> // for pthread_t, pthread_create(), pthread_join(),
// pthread_testcancel(), pthread_exit()

void * thread_function (void * unused);

int main()
{
pthread_t thread;
void *vp = NULL;
pthread_create (&thread, NULL, &thread_function, NULL);
pthread_join (thread, &vp);
if (vp != NULL)
{
printf("main(): %s\n", (char*)vp);
free(vp);
}

return 0;
}

class ThreadExitException
{
public:
/* Create an exception-signaling thread exit with `return_value': */
ThreadExitException (void * return_value)
: thread_return_value_ (return_value)
{printf("ThreadExitException(): %s\n", (char*)thread_return_value_);}
/* Actually exit the thread, using the return value provided
in the constructor: */
void * DoThreadExit(void)
{
printf("DoThreadExit(): %s\n", (char*)thread_return_value_);
pthread_exit (thread_return_value_);
return thread_return_value_;
}

private:
/* The return value that will be used when exiting the thread: */
void * thread_return_value_;
};

int should_exit_thread_immediately(void)
{
pthread_testcancel(); // cancelation point
return 1;
}

void do_some_work(void)
{
while (1)
{
/* Do some useful things here... */
void * return_value = malloc(1024);
strcpy((char*)return_value, "Goodbye!");
printf("do_some_work(): %s\n", (char*)return_value);

if (should_exit_thread_immediately())
{
throw ThreadExitException (return_value);
// throw ThreadExitException (/* thread's return value = */ NULL);
}
}
}

void * thread_function (void * unused)
{
try
{do_some_work();}
catch (ThreadExitException ex)
{
/* Some function indicated that we should exit the thread. */
return ex.DoThreadExit();
}

return NULL;
}

/*
g++ cxx-exit.cpp -o cxx-exit -lpthread
./cxx-exit
do_some_work(): Goodbye!
ThreadExitException(): Goodbye!
DoThreadExit(): Goodbye!
main(): Goodbye!
*/





Note:

In do_some_work(),
return_value[1024];
will be allocated on the stack and thus will not be visible in other threads (each thread has its own stack). As such, we must allocate it on the heap with malloc() or new in C++ (or we could use a static global variable, as in tsd).









Chapter_4     cleanup BACK_TO_TOP job-queue1



Comments

Popular posts from this blog

Contents