Я пытался перевести 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);
}
вывод моей программы:

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