【问题标题】:Receiving values from multiple threads in C从 C 中的多个线程接收值
【发布时间】:2012-09-10 14:46:00
【问题描述】:
#include<pthread.h>
#include<stdio.h>
#include<sys/stat.h>
#include<errno.h>

#define SIZE 3

/***I'm trying to send name of each file in a thread and trying to receive their respective size in main *******/

void *doit(void *name)
{
        int *size;
        struct stat st;
        char temp_name[30];
        memset(temp_name, '\0', sizeof(temp_name));
        strcpy(temp_name, (char *)name); //type casted
        stat(temp_name, &st);
        *size = st.st_size; //calculated the size

        printf("File name is: %s\n", temp_name);
        printf("File size is: %d\n", *size);
        pthread_exit((void *)size); //exited from thread
}

int main(int argc, char *argv[])
{
        pthread_t th_id[SIZE];
        int ret_val;
        int i;
        void **size[SIZE];
        for(i=0; i<SIZE;i++)
        {
                size[i] = (void **)malloc(30*sizeof(void *)); //allocated memory to void double pointer
                if(size[i] == NULL)
                {
                        printf("Memory not allocated to %dth member of size\n", (i+1));
                }
        }
        for(i=0; i<3; i++)
        {
          /*****Creating Thread**********/
                ret_val = pthread_create(&th_id[i], NULL, &doit, (void *)argv[1+i]);
                if(ret_val != 0)
                {
                        perror("Thread creation error\n");
                        exit(0);
                }
                pthread_join(th_id[i], size[i]);
                printf("Size is %d\n",**(int **)size[i]); //typecasted and printed
        }
        pthread_exit(NULL);
        return 0;
}

在这个程序中,我在第一次调用 pthread_join 后遇到了分段错误。传递第一个文件时,我在 main.js 中获得了正确的大小。但是在调用第二个文件期间,我遇到了分段错误。使用 gdb,我了解到“**size[1] 和 **size[2] 尽管 malloc 为 NULL。但是在 main 开始时,我在分配内存时没有收到错误消息。这应该意味着内存是最初分配的。请帮助我该怎么办。

【问题讨论】:

    标签: c multithreading pthreads return-value pthread-join


    【解决方案1】:
        int *size;
        struct stat st;
        char temp_name[30];
        memset(temp_name, '\0', sizeof(temp_name));
        strcpy(temp_name, (char *)name); //type casted
        stat(temp_name, &st);
        *size = st.st_size; //calculated the size
    

    您正在取消引用一个未初始化的指针。你永远不会让size 指向任何东西。

    【讨论】:

    • 您好@david,问题是当用于单个文件时,'doit' 函数的代码运行良好,我相信它现在应该适用于所有文件。但我认为问题肯定在 main 中,尤其是在 pthread_join 和 printf 中,当我进行类型转换时。
    • @user1660455:不值得尝试理解具有触发 UB 的已知错误的代码。修复错误,99% 的时间里,谜团就消失了。
    猜你喜欢
    • 1970-01-01
    • 2016-12-19
    • 2019-10-13
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多