1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| typedef struct ThreadPool ThreadPool;
ThreadPool* threadPoolInit(int min, int max, int queueSize) { ThreadPool* pool = (ThreadPool*)malloc(sizeof(ThreadPool)); do { printf("initialize begin\n"); if (pool == NULL) { printf("malloc failed"); break; } pool->threadIDs = (pthread_t*)malloc(sizeof(pthread_t) * max); pool->maxNum = max; pool->minNum = min; pool->liveNum = min; pool->busyNum = 0; pool->exitNum = 0; if (pthread_mutex_init(&pool->mutexPool, NULL) != 0 || pthread_mutex_init(&pool->mutexBusy, NULL) != 0 || pthread_cond_init(&pool->notEmpty, NULL) != 0 || pthread_cond_init(&pool->notFull, NULL) != 0) { printf("mutex or cond failed"); break; } memset(pool->threadIDs, 0, sizeof(pthread_t) * max); pool->taskQ = (Task*)malloc(sizeof(Task) * queueSize); pool->queueCapacity = queueSize; pool->queueFront = 0; pool->queueRear = 0; pool->shutdown = 0; pthread_create(&pool->managerID, NULL, manager, pool); for (int i = 0; i < min; ++i) { pthread_create(&pool->threadIDs[i], NULL, worker, pool); } printf("initialize complete\n"); return pool; } while (0); if (pool->threadIDs && pool) { free(pool->threadIDs); } if (pool && pool->taskQ) { free(pool->taskQ); } free(pool); return NULL; }
int threadDestory(ThreadPool* pool) { if (!pool)return -1; pool->shutdown = 1; pthread_join(pool->managerID, NULL); for (int i = 0; i < pool->liveNum; ++i) { pthread_cond_signal(&pool->notEmpty); } if (pool->taskQ) { free(pool->taskQ); } if (pool->threadIDs) { free(pool->threadIDs); } pthread_mutex_destroy(&pool->mutexBusy); pthread_mutex_destroy(&pool->mutexPool); pthread_cond_destroy(&pool->notEmpty); pthread_cond_destroy(&pool->notFull); free(pool); pool = NULL; return 0; }
|