/** * Create the thread pool. * * Pretty simple, just make sure the threads we create can't do anything * until we're done. */ ThreadPool* tpCreate(int num) { // Init: if (num < 0) // Sanity check return NULL; ThreadPool* tp = (ThreadPool*)malloc(sizeof(ThreadPool)); // Create the pool if (!tp) // Make sure it worked return NULL; tp->threads = (pthread_t*)malloc(sizeof(pthread_t)*num); // Create the thread array if (!tp->threads) { // Make sure it worked free(tp); return NULL; } #if HW3_DEBUG tp->tids = (int*)malloc(sizeof(int)*num); if (!tp->tids) { free(tp->threads); free(tp); return NULL; } int tid_i; for (tid_i=0; tid_i<num; ++tid_i) tp->tids[tid_i]=0; #endif // Locks and things pthread_mutexattr_init(&tp->mutex_type); pthread_mutexattr_settype(&tp->mutex_type,PTHREAD_MUTEX_ERRORCHECK_NP); pthread_mutex_init(&tp->task_lock, &tp->mutex_type); sem_init(&tp->r_num_mutex, 0, 1); sem_init(&tp->w_flag_mutex, 0, 1); sem_init(&tp->r_entry, 0, 1); sem_init(&tp->r_try, 0, 1); sem_init(&tp->state_lock, 0, 1); pthread_cond_init(&tp->queue_not_empty_or_dying, NULL); // Basic fields tp->N = num; tp->r_num = 0; tp->w_flag = 0; tp->state = ALIVE; tp->tasks = osCreateQueue(); // Create threads! // No need to lock anything, the threads are now allowed // to read the task queue and the state anyway - neither // of them are going to be touched here. int i,ret; for (i=0; i<num; ++i) { ret = pthread_create(tp->threads + i, NULL, thread_func, (void*)tp); PRINT("Creating thread %d, return value: %d\n",i+1,ret); } // Return the ThreadPool return tp; }
ThreadPool *tpCreate(int numOfThreads) { if (numOfThreads < 1) {//ERROORRRREE return NULL; } ThreadPool *tp = malloc(sizeof(*tp)); if(!tp){ return NULL; } tp->taskQueue = osCreateQueue(); if (tp->taskQueue == NULL) {//ERROORRRREE return NULL; } tp->numOfThreads = numOfThreads; if (pthread_cond_init(&(tp->cond_taskQueueNotEmpty), NULL)) {//ERROORRRREE return NULL; } pthread_mutexattr_t mutexattr_t; if (pthread_mutexattr_init(&mutexattr_t)) {//ERROORRRREE return NULL; } if (pthread_mutexattr_settype(&mutexattr_t, PTHREAD_MUTEX_ERRORCHECK)) {//ERROORRRREE return NULL; } if (pthread_mutex_init(&(tp->mutex_taskQueue_lock), &mutexattr_t)) {//ERROORRRREE return NULL; } if (pthread_mutexattr_destroy(&mutexattr_t)) {//ERROORRRREE return NULL; } if (sem_init(&(tp->sem_tpDestroyWasInvoked), 0, 1)) {//ERROORRRREE return NULL; } tp->threadIdArray = malloc(sizeof(pthread_t)*numOfThreads); if(!(tp->threadIdArray)){//ERROORRRREE return NULL; } tp->tpDestroyNeedsLock = 0; int i; for (i = 0; i < numOfThreads; ++i) { pthread_t x; if (pthread_create(&x, NULL, getAndExecuteTasksForever, (void *) tp)) {//ERROORRRREE return NULL; } (tp->threadIdArray)[i] = x; } return tp; }