2011-07-11 51 views
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)); 

} 

显然,这个功能没有被每一个线程调用,我想不通为什么。你能帮我解决这个问题吗?

+0

你怎么知道函数没有被每个线程调用? Printf不是线程安全的;除非你同步访问它,否则你不会得到你期望的结果。 – antlersoft

+0

@antlersoft:在Linux的libc中,printf'实际上是线程安全的。 – 2011-07-11 18:02:49

+0

创建线程后你在做什么? –

回答

2

首先,小挑剔,写作(*sottoVettore).dimensione)的地道方式是sottoVettore->dimensione

退出main()时,包含所有线程的进程将退出。我知道你说你加入了你的实际代码,所以这不应该是一个问题,但如果你没有加入测试代码,那么这可能是一个问题。

也可能问题不在于每个线程中的代码没有执行,而是这些语句实际上没有达到stdout。您可能想在calcolaMassimo的末尾尝试fflush(stdout),看看是否会改变这些事情。