【问题标题】:How to pass an array properly to a threaded function with a structure如何将数组正确传递给具有结构的线程函数
【发布时间】:2018-04-03 00:38:11
【问题描述】:

这几天我一直在苦苦思索,因为我似乎找不到解决这个问题的好方法。我需要使用结构将两个数组传递给线程函数。一个数组是我需要求和的结构,另一个是需要存储求和结果的地方,然后我需要在主程序中最后一次对它们求和以获得总值。

#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#define NUMBER_OF_THREADS 2


typedef struct
{
    double s[NUMBER_OF_THREADS];
    double a[];
    int tid;
} parmListType;


void *sum_arr(void *parms)
{   

    pthread_exit(NULL);
}

int main(int argc, char **argv)
{
    pthread_t threads[NUMBER_OF_THREADS];
    int status, i;
    double arr[1000000]={};
    double sum[NUMBER_OF_THREADS];

    printf("debug_size_arr: %ld\n",sizeof(arr)/sizeof(double));
    for(int i=0;i<sizeof(arr)/sizeof(double);i++)
    {
     arr[i]=i;
    }
    parmListType *parms;

    for(i=0; i<NUMBER_OF_THREADS; i++)
    {
        printf("debug: Main here. Creating thread %d\n", i);

        // dynamically create a structure to hold the parameter list 
        parms = (parmListType *)malloc( sizeof(parmListType));

        //printf("debug_sizeof_paramA: %ld\n",sizeof(parms->a)); 
        //parms->s[NUMBER_OF_THREADS/sizeof(double)]= *sum;
        parms->tid = i;


        status = pthread_create(&threads[i], NULL, sum_arr, (void *) parms);

        if(status != 0)
        {
             printf("oops. pthread_create returned error code %d\n", status);
            exit(-1);
        }
      printf("first for\n");
    }


     for(i=0; i<NUMBER_OF_THREADS; i++)
     {
        status=pthread_join(threads[i], NULL);
     }
    exit(0);
}
//// there are loads of errors in this code, I need guidance about how Im 
////supposed to set this up right.   

【问题讨论】:

  • "source_file.c:10:12: 错误:字段的类型不完整 'double []'" ???你对这个成员有什么计划?很抱歉,但在尝试 C 中的多线程之前,您应该学习更多的 C 代码。C 中的线程并不容易。为什么需要一个数组来存储总和,也就是单个值?如果你直接写作业会更容易理解。
  • 您只能将像double a[]; 这样的灵活数组成员 (FAM) 作为结构的最后一个元素。
  • 你在第一个循环中像愤怒一样泄漏内存。你分配了一个parmListType 并将它传递给线程,但是线程并没有释放它(或做任何其他有用的事情),并且主代码没有跟踪它。
  • 我熟悉大量命令式语言,我从未使用过 C 语言,也从未使用过线程,这是我的操作系统课程的作业。就像我在 cmets 中所说的那样,有很多小错误,我编译它,但我只是在试验时破坏了它。
  • 那么,我相信您正在学习使用版本控制系统?这就是你如何防止编辑按照某种定义有效的代码的损失。

标签: c multithreading pthreads


【解决方案1】:

你可以做类似下面的 st:

struct ThreadArgs
{
    int type;
    //others
};

void* Thread(void* thread_args)
{
    int type;
    pthread_detach(pthread_self());
    type = ((struct ThreadArgs *) thread_args)->type;
    return NULL;
}

int main()
{
    pthread_t thread_id;
    struct ThreadArgs* thread_args;
    thread_args = (struct ThreadArgs *) malloc(sizeof(struct ThreadArgs));
    if (thread_args == NULL)
        PanicWithError("malloc() failed");
    thread_args->type = 1;
    if (pthread_create(&thread_id, NULL, Thread, (void *) thread_args) != 0)
         PanicWithError("pthread_create() failed");
    while (1)
    {}
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多