gpt4 book ai didi

c - 不同线程中的全局变体是否意味着不同的变体?

转载 作者:太空宇宙 更新时间:2023-11-04 03:16:42 24 4
gpt4 key购买 nike

我尝试将OpenMP 中的parallel execution of sections 翻译成pthread 程序。我用一个全局变体(sect_left)来记录要执行的总节数,但似乎不同线程中的变体(sect_left)是两个不同的变体和有独立的值(value)观。

为了让我的程序更容易理解,我将其简化如下:

#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);
}

the output of my program is:

enter image description here

如果不同线程中的全局变量是不同的变量,如何表示一个全局变量,无论有多少个线程,都是整个程序中唯一的一个?

谢谢!

最佳答案

我认为发生了以下情况:

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 设置单独的计数器?或 bool 标志 sec_l​​eft_initialized。

关于c - 不同线程中的全局变体是否意味着不同的变体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50818342/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com