// Return true to let pool to handle the thread: reuse or delete. bool ThreadPool::on_thread_run(ThreadHandle* thread) { // execute one thread with one specified task. // _LogDebug_("ThreadPool", "run thread handle : %d", thread); // Lock the thread attributes. ThreadBase* task = NULL; { // We won't keep this lock during the running of the task. // And the task object will be not delete before it's run() has been completed. AutoLock(thread->lock); task = thread->task; } // if (task) { _LogDebug_("ThreadPoll", "run thread's task: %d", thread->task); return task->run(); } else { _LogDebug_("ThreadPool", "No task to run, send to idle set."); // No task for thread, so just return ture, and according to the reuse, pool will reuse it or delete this thread. return true; } }
BEGIN_ZKIT void* ThreadBase::threadFunc(void *arg) { ThreadBase *thread = (ThreadBase *)arg; if (thread == 0) { return 0; // error. } while (!thread->isTerminated()) { if (thread->run() < 0) { printf("\nthread=%d exit because of return value!", thread->getThreadId()); break; } } thread->threadStopped(); printf("\nthread exit: %d", thread->getThreadId()); return 0; }
void* ThreadBase::runInThread(void *arg) { //派生子线程复写run()方法 //向上转型,ThreadBase指针指向子对象(实现多态) //参数: *arg 为pthread_create()传入的this(即具体的子线程) ThreadBase *pthread = static_cast<ThreadBase*> (arg); pthread->run(); return NULL; }