#include <iostream> #include <vector> #include <pthread.h> #include "destory_free_while.h" using namespace std; Worker::Worker() { shutdown = false; num_thread = 10; } void Worker::start() { tids.resize(num_thread); for (int i = 0; i <num_thread ; ++i) { if (pthread_create(&tids[i], NULL, sleeping, this) == 0) { cout << "thread start complete" << endl; } } } Worker::~Worker() { cout << "begin destory instance" << endl; shutdown = true; for(unsigned int i=0; i<tids.size(); i++) { pthread_join(tids[i], NULL); } } void* Worker::sleeping(void* arg) { Worker* work = (Worker*)arg; while(true) { cout << "." << flush; sleep(1); if(work->shutdown) { cout << " destory instance , thread quit" << endl; break; } } } /* vim: set ts=4 sw=4 sts=4 tw=100 */
#ifndef DESTORY_FREE_WHILE_H #define DESTORY_FREE_WHILE_H #include <vector> #include <pthread.h> class Worker { public: Worker(); ~Worker(); void start(); public: static void* sleeping(void* arg); public: std::vector<pthread_t> tids; int num_thread; bool shutdown; }; #endif // DESTORY_FREE_WHILE_H
#include <iostream> #include "destory_free_while.h" using namespace std; int main() { Worker worker; worker.start(); sleep(20); cout << "program exit" << endl; }