/** * Destroy thread pool (called by main thread) */ void tpool_destroy(tpool_t *tp) { if (!tp) return; if (!(tp->status & TPOOL_STATUS_INITED)) goto destroy_end; // forced to cancel all actived threads if (tp->cur_total > 0) { int i = 0; struct tpool_thread *t; // force to cancel threads that is executing task function while (i < tp->max_total) { t = &tp->threads[i++]; if (t->status & TPOOL_THREAD_TASK) { // NOTE: If it is me, I should wait other threads, so can not die first. // But forced to call cleanup is required. if (pthread_equal(t->tid, pthread_self())) { tpool_thread_cleanup((void *) t); debug_printf("run cleanup for thread[%d] that is myself (TID:%p)", t->index, t->tid); } else { pthread_cancel(t->tid); debug_printf("cancel thread[%d] that is executing task (TID:%p)", t->index, t->tid); } } } // cancel & wait tpool_do_cancel(tp, 1); } pthread_mutex_destroy(&tp->mutex); // clean inited status tp->status ^= TPOOL_STATUS_INITED; destroy_end: if (tp->status & TPOOL_STATUS_ONHEAP) free(tp); }
/** * Destroy thread pool (called by main thread) */ void tpool_destroy(tpool_t *tp) { if (!tp) return; if (!(tp->status & TPOOL_STATUS_INITED)) goto destroy_end; // forced to cancel all actived threads if (tp->cur_total > 0) { int i; // force to cancel threads that is executing task function for (i = 0; i < tp->max_total; i++) { if (tp->threads[i].status & TPOOL_THREAD_TASK) { // NOTE: If it is me, I should wait other threads, so can not die first. // But forced to call cleanup is required. if (pthread_equal(tp->threads[i].tid, pthread_self())) { tpool_thread_cleanup((void *) &tp->threads[i]); debug_printf("Force to run cleanup function for thread[%d], because it is me (TID:%p)\n", i, tp->threads[i].tid); continue; } pthread_cancel(tp->threads[i].tid); debug_printf("Force to cancel thread[%d], because it is executing task (TID:%p)\n", i, tp->threads[i].tid); } } // cancel & wait tpool_do_cancel(tp, 1); } // clean inited status tp->status ^= TPOOL_STATUS_INITED; destroy_end: if (tp->status & TPOOL_STATUS_ONHEAP) free(tp); }