1
我正在用线程逼近C编程,我无法使该程序正常工作。基本上有一个向量包含k个元素,n个线程,每个线程必须计算其k/n个元素的最大值。线程执行问题
我的代码是(请注意这不是整个代码):
// Struct code used later
struct maxStruct
{
double *vettore;
int dimensione;
};
// Gathering data input from user
[ . . . ]
vector = (double *) malloc (dimensione * sizeof(double));
pid_thread = (int *) malloc (numero_thread * sizeof(int));
thread = (pthread_t *) malloc (numero_thread * sizeof(pthread_t));
// Generating the vector
[ . . . ]
for (i = 0; i < numero_thread; i++)
{
e = generaStruct(i, vettore, dimensione, numero_thread);
if (status = pthread_create(&thread[i], NULL, calcolaMassimo, (void *) e))
{
pthread_perror("pthread_join", status);
exit(1);
}
}
//Note that the function doesn't calculate the max, I've coded it in this way
//in order to see whether it was being called by each thread and apparently it is not.
void *calcolaMassimo(void * e)
{
printf("Sono chiamata!!\n");
struct maxStruct *sottoVettore = e;
printf("Dimensione: %d\n", ((*sottoVettore).dimensione));
}
显然,这个功能没有被每一个线程调用,我想不通为什么。你能帮我解决这个问题吗?
你怎么知道函数没有被每个线程调用? Printf不是线程安全的;除非你同步访问它,否则你不会得到你期望的结果。 – antlersoft
@antlersoft:在Linux的libc中,printf'实际上是线程安全的。 – 2011-07-11 18:02:49
创建线程后你在做什么? –