title: How to dynamically set number of threads using OpenMp
body: <p>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:</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;signal.h&gt;
  #include&lt;unistd.h&gt;
  #include&lt;omp.h&gt;
  
  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;
  }
  </code></pre>
  
  <p>Here I compiled the code with <code>gcc filename.c -o file -fopenmp</code>. Since I set 4 threads initially I can see 4 threads running. Then during runtime I raise a signal using <code>kill -USR1 process_id</code> .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 <code>omp_parallel</code> construct. Please suggest a solution.</p>