I should create 43 threads in a particular process (there are multiple processes here in my problem, so let’s call process P6). I created 43 threads and I use a semaphore with 6 permissions to solve the problem so that at any moment no more than 6 threads run simultaneously (the semaphore has 6 permissions in main). I also used a semaphore with 38 permissions to execute the first 38 threads (semaphore_4). The other 2 semaphores (semaphore_2 and semaphore_3 are initialized with 0 permissions). My question is, why are there still threads in the last 5 that terminate before thread 13. Also, I’m not allowed to use “sleep()” and “usleep()”.
sem_wait(param->semaphore);
sem_wait(param->semaphore_4);
info(BEGIN, 6, param->thread_num); //informs the tester of start the execution of a thread
pthread_mutex_lock(param->mutex);
(*param->active_threads)++;
pthread_mutex_unlock(param->mutex);
sem_post(param->semaphore_4);
if(param->thread_num == 13) {
sem_wait(param->semaphore_2);
}
while (*param->active_threads > 38 && *param->active_threads <= 42) {
sem_wait(param->semaphore_3);
}
if(*param->active_threads == 43) {
printf("%dn", *param->active_threads);
*param->active_threads = 0;
sem_post(param->semaphore_2);
active = 1;
}
if(active) {
sem_post(param->semaphore_3);
}
info(END, 6, param->thread_num); //informs the tester of the end of the execution of a thread
sem_post(param->semaphore);
locki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.