#include <pthread.h> #include <stdio.h> #include <unistd.h> class testClass { public: testClass(); ~testClass(); private: static void *thread_func(void*); pthread_t thrid; }; testClass::testClass() { printf("[%s:%d,%s]\n", __FILE__, __LINE__, __func__); pthread_create(&thrid, NULL, thread_func, this); } testClass::~testClass() { printf("[%s:%d,%s]\n", __FILE__, __LINE__, __func__); pthread_cancel(thrid); pthread_join(thrid, NULL); } void* testClass::thread_func(void *param) { int i=0; testClass *self = (testClass*)param; printf("[%s:%d,%s]thread start\n", __FILE__, __LINE__, __func__); while(1) { printf("[%s:%d,%s]%d\n", __FILE__, __LINE__, __func__, i++); sleep(1); } printf("[%s:%d,%s]thread stop\n", __FILE__, __LINE__, __func__); return (void*)0; } int main(int argc, char **argv) { testClass *test; test = new testClass(); sleep(10); delete test; return 0; } # ./a.out [test.cpp:18,testClass] [test.cpp:33,thread_func]thread start [test.cpp:35,thread_func]0 [test.cpp:35,thread_func]1 [test.cpp:35,thread_func]2 [test.cpp:35,thread_func]3 [test.cpp:35,thread_func]4 [test.cpp:35,thread_func]5 [test.cpp:35,thread_func]6 [test.cpp:35,thread_func]7 [test.cpp:35,thread_func]8 [test.cpp:35,thread_func]9 [test.cpp:24,~testClass]

台南小新 發表在 痞客邦 PIXNET 留言(0) 人氣()