ThreadPool icon indicating copy to clipboard operation
ThreadPool copied to clipboard

Possible concurrent bugs

Open neutron-L opened this issue 8 months ago • 0 comments

Hello, I think there is a concurrency issue with adding tasks and thread execution methods in the code. Fragment in thread execution method threadExecutor:

		pthread_mutex_lock(&pool->queuemutex); // Lock the queue mutex
// try to  get job

if (presentJob == NULL || pool->suspend) {
pthread_mutex_unlock(&pool->queuemutex); // Unlock the mutex

// Maybe at this time, main thread add a job and find there are not waiting threads

			pthread_mutex_lock(&pool->condmutex); // Hold the conditional mutex
			pool->waitingThreads++; // Add yourself as a waiting thread
}

pthread_cond_wait(&pool->conditional,
			                  &pool->condmutex); // Idle wait on conditional

Add fragments from method mt_add_job:

pthread_mutex_lock(&pool->queuemutex); // Inserting the job, lock the queue

// add job

	if(pool->waitingThreads >
	   0) { 
// signal waiting work thread
	}

	pthread_mutex_unlock(&pool->queuemutex); // Finally, release the queue

Perhaps the thread checked the queue and found that there were no tasks waiting, but before updating x, the main thread joined the queue for a new task and checked x, only to find that there were no threads waiting, resulting in the worker thread not being awakened in a timely manner. I'm not sure if there's a problem with my understanding, thank you

neutron-L avatar Mar 02 '25 10:03 neutron-L