gpt4 book ai didi

c - 为什么线程从数组中随机加载数据?

转载 作者:行者123 更新时间:2023-11-30 16:38:10 24 4
gpt4 key购买 nike

我是线程新手,我正在尝试创建一个程序,其中四个线程使用全局数组中的值进行一些并行计算。但是,线程没有按顺序加载数据的问题。

#define QUARTER 64
#define RANGE_STEP 256

struct thread_data
{
unsigned start;
unsigned stop;
__m256* re_fc;
__m256* im_fc;
};

#define NUM_THREADS 4
struct thread_data thread_data_array[NUM_THREADS];

void *routine(void *thread_info)
{
int n,t;
unsigned t_start,t_stop;
__m256 *Re_fac , *Im_fac;
struct thread_data *mydata;
mydata = (struct thread_data*) thread_info;
t_start = mydata->start;
t_stop = mydata->stop;
Re_fac = mydata->re_fc;
Im_fac = mydata->im_fc;

t = t_start;
for (n = t_start; n < t_stop; n += 8)
{
// computations
RE_m256_fac = Re_fac[t];
IM_m256_fac = Im_fac[t];
// computations
t++;
}
pthread_exit(NULL);
}

int main()
{
unsigned t,i=0;
for(t=0;t<RANGE_STEP;t+=QUARTER)
{
thread_data_array[i].start = t;
thread_data_array[i].stop = t+QUARTER;
thread_data_array[i].re_fc = RE_factors;
thread_data_array[i].im_fc = IM_factors;
pthread_create(&threads[i],NULL,routine,(void *)&thread_data_array[i]);
i++;
}
for(i=0; i<NUM_THREADS; i++)
{
int rc = pthread_join(threads[i], NULL);
if (rc)
{
fprintf(stderr, "failed to join thread #%u - %s\n",i, strerror(rc));
}
}
}

我所说的问题发生在 for() 循环内的线程例程中,恰好使用这两个加载指令RE_m256_fac = Re_fac[t];IM_m256_fac = Im_fac[t]; 加载的数据不正确...我认为索引 t 是一个局部变量,所以不需要同步,或者我是错了?

最佳答案

经过一番挖掘后发现,由于我正在从全局共享数组中读取数据,因此我必须使用互斥机制来防止互斥,如下所示:

void *routine(void *thread_info)
{
int n,t;
unsigned t_start,t_stop;
__m256 *Re_fac , *Im_fac;
struct thread_data *mydata;
mydata = (struct thread_data*) thread_info;
t_start = mydata->start;
t_stop = mydata->stop;
Re_fac = mydata->re_fc;
Im_fac = mydata->im_fc;

t = t_start;
for (n = t_start; n < t_stop; n += 8)
{
pthread_mutex_lock(&mutex);
// computations
RE_m256_fac = Re_fac[t];
IM_m256_fac = Im_fac[t];
// computations
pthread_mutex_unlock(&mutex);
t++;
}
pthread_exit(NULL);
}

从那时起,我可以看到线程正在从共享数组正确加载值。

关于c - 为什么线程从数组中随机加载数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47597802/

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