3

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.

Jonny Henly
  • 4,023
  • 4
  • 26
  • 43
Chinnu
  • 85
  • 10
  • You're going about this the wrong way, the number of threads cannot be redefined inside of a parallel section. You need to exit the parallel section, change the number of threads, then re-enter the parallel section using some type of nested loop setup. – Jonny Henly Jun 29 '16 at 06:11
  • Why do you want to change the number of threads in a parallel region? You can control which threads in a parallel region do work and the remaining threads idle so I don't think you need to reduce the number of threads as long as you have enough to start with. – Z boson Jun 29 '16 at 06:24
  • I have to use such a scenario for one of my projects.For this i am writing a sample application like above.Are there any otherways to control these threads inside a parallel region – Chinnu Jun 29 '16 at 06:29
  • @Jonny Henly, how can I exit from parallel section.do u mean to exit from the entire process and restart it again??I have to control threads without interrupting the current execution – Chinnu Jul 01 '16 at 08:36
  • @Chinnu are you still having trouble with this? If so I can post an answer with an example of the scenario I mentioned above. – Jonny Henly Jul 07 '16 at 08:12
  • @Jonny Henly.I have trouble with controlling number of threads at the run time .I read that I can't change the nu_thread value at run time.But I am need of such a thing.is there any other way to accomplish this.please post your example – Chinnu Jul 07 '16 at 08:50

0 Answers0