extern int threadPoolInitialize(int n) { if (threadPool != NULL) { return 0; } if (n < 1) { return -1; } Thread* threads = (Thread*) malloc(n * sizeof(Thread)); int maxLength = QUEUE_MAX_SIZE; size_t queueSize = maxLength * sizeof(ThreadPoolTask); ThreadPoolTask** queue = (ThreadPoolTask**) malloc(queueSize); threadPool = (ThreadPool*) malloc(sizeof(ThreadPool)); threadPool->terminated = 0; threadPool->threads = threads; threadPool->threadsLen = n; threadPool->queue.data = queue; threadPool->queue.length = 0; threadPool->queue.maxLength = maxLength; threadPool->queue.current = 0; threadPool->queue.last = 0; threadPool->queue.full = 0; semaphoreCreate(&(threadPool->queue.mutex), 1); semaphoreCreate(&(threadPool->queue.wait), 0); semaphoreCreate(&(threadPool->queue.submit), 0); int i; for (i = 0; i < n; ++i) { threadCreate(&(threads[i]), worker, NULL); } return 0; }
static ThreadPoolTask* sumbit(void* (*routine)(void*), void* param, int toFront) { if (threadPool == NULL) { routine(param); return NULL; } ThreadPoolQueue* queue = &(threadPool->queue); semaphoreWait(&(queue->mutex)); if (threadPool->terminated) { semaphorePost(&(queue->mutex)); return NULL; } if (queue->current == (queue->last + 1) % queue->maxLength) { queue->full = 1; semaphorePost(&(queue->mutex)); semaphoreWait(&(queue->wait)); semaphoreWait(&(queue->mutex)); } if (threadPool->terminated) { semaphorePost(&(queue->mutex)); return NULL; } ThreadPoolTask* task = (ThreadPoolTask*) malloc(sizeof(ThreadPoolTask)); task->routine = routine; task->param = param; semaphoreCreate(&(task->wait), 0); if (toFront) { queue->current = (queue->current - 1 + queue->maxLength) % queue->maxLength; queue->data[queue->current] = task; } else { queue->data[queue->last] = task; queue->last = (queue->last + 1) % queue->maxLength; } semaphorePost(&(queue->mutex)); semaphorePost(&(queue->submit)); return task; }
Flag flagCreate(void) { return (Flag) semaphoreCreate(1); }