I am not sure that the name reflects what I ask here, but this is the best way I can do without a very short title. I am trying to implement a worker thread model in pthreads . I want to create a set of threads from the main function, after which the main thread delegates the task to the worker and waits for all the threads to finish before assigning them the next task (in fact, the requirement is to arrange the stream in a block similar to the CUDA programming model, but on the CPU. Although this does not apply to the current issue). The job array is used to indicate the type of job for each thread. I have currently implemented this with semaphores that impose lively expectation. I am looking for ways to make it so that threads sleep and wake up only when they are required, and not poll continuously.
Function performed by each thread
volatile int jobs[MAX_THREADS];
The main function is as follows
int main() { sem_init(&semaphore, 0, 0); jobs[0...MAX_THREADS] = 0; spawn_threads();
The problem with this implementation is that the main thread is busy waiting for all workflows to complete, and the workflows are also constantly polling an array of jobs to check for a new job. Is there a better way to do this when the threads fall asleep and wake up, when necessary, along the lines of a single handler and using pthread_kill() , but this is pretty messy with a separate signal handler.
source share