以下代码使用gcc(4.1.2 20080704)生成错误且不一致的输出,但使用icc(版本11.1)生成正确和预期的输出.但是当我将thread_data_array []定义从main()移动到global(紧跟在struct thread_data定义之后)时,它对两个编译器都可以正常工作.我不明白为什么这种改变应该有所不同.我想以递归方式生成线程,所以我需要从函数调用它而不是定义为全局.有人可以解释代码有什么问题吗?
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 4
struct thread_data {
int thread_id;
int sum;
};
/* struct thread_data thread_data_array[NUM_THREADS]; */
void *p_task(void *threadarg)
{
struct thread_data *my_data;
int taskid;
int sum;
my_data = (struct thread_data *) threadarg;
taskid = my_data->thread_id;
sum = my_data->sum;
printf("Thread #%d with sum %d\n", taskid, sum);
for ( sum = 0; sum < 000000000; sum++ ) {
for ( taskid = 0; taskid < 000000000; taskid++ ) {
sum+=taskid;
}
}
return my_data;
}
int main ()
{
struct thread_data thread_data_array[NUM_THREADS]; /*this does not work*/
pthread_t threads[NUM_THREADS];
int rc;
long t;
for ( t = 0; t < NUM_THREADS; t++ ) {
thread_data_array[t].thread_id = t;
thread_data_array[t].sum = (int) t*2;
rc = pthread_create( &threads[t], NULL, p_task, (void *) &thread_data_array[t] );
}
pthread_exit(NULL);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
好吧,我的第一个想法是主线程实际上正在退出,并在其他线程完成之前使用它的堆栈帧.从我记得的pthreads(这是十多年前,与DCE一起使用),除了堆栈大小之外,主线程绝对没有什么特别之处.
如果数组被声明为全局,则退出main将不会对它产生影响,但是,如果它在堆栈框架中main,则在退出后我会非常小心地使用它.
我部分基于猜测,因为你还没有真正解释你所看到的行为.
我建议在pthread_exitin 之前插入以下代码main:
for (t = 0; t < NUM_THREADS; t++ )
pthread_join (threads[t], NULL);
Run Code Online (Sandbox Code Playgroud)