【发布时间】:2017-12-01 16:46:32
【问题描述】:
我是线程新手,我正在尝试创建一个程序,其中四个线程使用全局数组中的值进行一些并行计算。但是,线程没有按顺序加载数据的问题。
#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 是一个局部变量,所以不需要同步,还是我错了?
【问题讨论】:
-
thread_data_array是什么? -
t可能是一个局部变量,但它用于索引的数组thread_data_array显然是跨线程共享的。展示它是如何构造的,并验证routine()中的 for 循环是否正确。 -
thread_data类型的thread_data_array用于传递每个线程的参数,它被声明为全局(请参阅结构声明后的代码编辑)。我仔细检查了 routine 中的for()循环,它按预期工作。 -
@bnaecker :
thread_data_array不仅包含索引,还包含一堆参数,正如您在 struct 声明中看到的那样。
标签: c arrays multithreading