Глобальный вариант в разных потоках означает разные варианты? - PullRequest
0 голосов
/ 12 июня 2018

Я пытался перевести parallel execution of sections в OpenMP в pthread программу.Я использую глобальный вариант (sect_left) для записи общего числа секций, которые должны быть выполнены, но кажется, что вариант (sect_left) в разных потоках - это два разных варианта и имеют независимые значения.

Чтобы облегчить понимание моей программы, я упростил ее, как показано ниже:

#include <pthread.h>

define get_tid() syscall(__NR_gettid)

int sect_left = -1;    //the total number of sections to be execute
int nthr_in_sect = 0;  //the number of threads entered the sections
pthread_mutex_t mt_sect; 

void entering_sections(int numberofsections)
{
  pthread_mutex_lock(&mt_sect);
  if(nthr_in_sect <= 0){    //if this is the first thread come in
    sect_left = numberofsections;  //set number of sections when first thread come in
    printf("%d set number of sections: %d\n", get_tid(), sect_left);
  }
  nthr_in_sect++;   //the number of threads entered +1
  pthread_mutex_unlock(&mt_sect);
}

void leaving_sections()
{
  pthread_mutex_lock(&mt_sect);
    nthr_in_sect--;  //the number of threads in sections -1 after leaving sections
  pthread_mutex_unlock(&mt_sect);
}

int get_section()
{
  if (sect_left < 0) return (-1);

  pthread_mutex_lock(&mt_sect);
    int s = --(sect_left);   //fetch a section and the total number -1
  pthread_mutex_unlock(&mt_sect);

  return (s);
}

static void * func(void *arg)
{
  {
    int caseid = -1;
    entering_sections(2);
    for(;;)
    {
      //if there is no section remain
      if((caseid = get_section()) < 0) break; 

      switch(caseid)
      {
        case 0:
          printf("section 11 threadID = %d\n",get_tid());
          break;
        case 1:
          printf("section 22 threadID = %d\n",get_tid());
          break;
      }
    }
    leaving_sections();
  }
}

void main()
{
  pthread_mutex_init(&mt_sect, NULL);

  pthread_t thr;
  pthread_create(&thr,NULL,func, (void *) 0);

  (*func)((void *) 0);

  pthread_join(thr,NULL);

  pthread_mutex_destroy(&mt_sect);
}

вывод моей программы:

enter image description here

Если глобальный вариант в разных потоках - это разные варианты, как представить глобальный вариант, единственный во всей программе, независимо от количества потоков?

Спасибо!

1 Ответ

0 голосов
/ 12 июня 2018

Я думаю, что происходит следующее:

nthr_in_sect == 0
4789: entering_sections(2);
sec_left = 2
4789: print section strings
sec_left = -1
4789: leaving_sections();
nthr_in_sect == 0 (again)
4790: entering_sections(2);
sec_left = 2
4790: print section strings
sec_left = -1
4790: leaving_sections();
nthr_in_sect == 0 (again)

Итак, программа работает так, как написано.Первый поток заканчивается так быстро, что второй начинается снова, потому что он думает, что это первый.

Может быть, у вас должны быть отдельные счетчики для nthr_entered_sect и nthr_left_sect?Или логический флаг sec_left_initialized.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...