Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 线程执行问题_C_Multithreading_Pthreads_Execution - Fatal编程技术网

C 线程执行问题

C 线程执行问题,c,multithreading,pthreads,execution,C,Multithreading,Pthreads,Execution,我正在使用线程进行C编程,但我无法让这个程序正常工作。基本上有一个包含k个元素的向量,n个线程,每个线程必须计算其k/n元素的最大值 我的代码是(请注意它不是全部代码): //以后使用的结构代码 结构maxStruct { 双倍*vettore; 整数维; }; //收集用户输入的数据 [ . . . ] 向量=(双*)malloc(维数*sizeof(双)); pid_线程=(int*)malloc(numero_线程*sizeof(int)); 线程=(pthread_t*)malloc(n

我正在使用线程进行C编程,但我无法让这个程序正常工作。基本上有一个包含k个元素的向量,n个线程,每个线程必须计算其k/n元素的最大值

我的代码是(请注意它不是全部代码):

//以后使用的结构代码
结构maxStruct
{
双倍*vettore;
整数维;
};
//收集用户输入的数据
[ . . . ]
向量=(双*)malloc(维数*sizeof(双));
pid_线程=(int*)malloc(numero_线程*sizeof(int));
线程=(pthread_t*)malloc(numero_thread*sizeof(pthread_t));
//生成向量
[ . . . ]
对于(i=0;i

显然,每个线程都没有调用这个函数,我不知道为什么。你能帮我解决这个问题吗?

首先,一个小小的吹毛求疵,编写
(*sottovetore.dimensione)的惯用方法是
sottovetore->dimensione

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


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

您如何知道函数没有被每个线程调用?Printf不是线程安全的;除非你同步对它的访问,否则你不会得到你期望的结果。@antlersoft:Linux
s libc
printf`实际上是线程安全的。创建线程后你在做什么?@KarlBielefeldt我认为它应该执行calcolaMassimo的代码,每个线程计算每个子向量的最大值,然后我会调用一个pthread_join,以获得每个线程找到的最大值…@hourted86:好吧,问题似乎正是Abhay Buch在回答中所说的-您需要在创建的线程上进行连接,等待它们完成后再退出,或者您需要通过调用
pthread_exit()退出
main()
而不是
main()
中的
exit()
,以便在所有线程完成之前,进程保持活动状态。
// 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));

}