线程执行问题

时间:2011-07-11 17:53:07

标签: c multithreading pthreads execution

我正在使用线程进行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));

}

显然每个线程都没有调用此函数,我无法弄清楚原因。你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

首先,一个次要的选择,写(*sottoVettore).dimensione)的惯用方式是sottoVettore->dimensione

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

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