I am trying to control running threads using OpenMp. What I need is to set number of running threads according to certain condition. I am using signal handler to control the thread. I have written the following code:
#include<stdio.h>
#include<signal.h>
#include<unistd.h>
#include<omp.h>
int i;
int num_threads = 4;
void sig_handler(int signo) {
if (signo == SIGUSR1) {
printf("\n receivd signal\n");
omp_set_num_threads(2);
} else if (signo == SIGKILL)
printf("received SIGKILL\n");
else if (signo == SIGSTOP)
printf("received SIGSTOP\n");
}
int main(void) {
i = 0;
if (signal(SIGUSR1, sig_handler) == SIG_ERR)
printf("\ncan't catch SIGUSR1\n");
if (signal(SIGKILL, sig_handler) == SIG_ERR)
printf("\ncan't catch SIGKILL\n");
if (signal(SIGSTOP, sig_handler) == SIG_ERR)
printf("\ncan't catch SIGSTOP\n");
omp_set_num_threads(num_threads);
#pragma omp parallel
while(1) {
i++;
printf("OPENMP USING SIGHANDLER::%d\n",i);
sleep(1);
}
return 0;
}
Here I compiled the code with gcc filename.c -o file -fopenmp
. Since I set 4 threads initially I can see 4 threads running. Then during runtime I raise a signal using kill -USR1 process_id
.Here my program received the signal,after that I have to change number of threads from 4 to 2.But this time I am getting initial 4 threads .I cant change or control the threads inside omp_parallel
construct. Please suggest a solution.