Проблемы с pthread_create () - PullRequest
       14

Проблемы с pthread_create ()

0 голосов
/ 21 сентября 2018

Итак, я задал вопрос ранее о конкретной проблеме.Я просмотрел другие вопросы на этом сайте, но большинство из них не касаются моей проблемы, хотя я думаю, что этот вопрос будет полезен для других начинающих.Итак, вот код.

(pi.h) Как устроена моя структура

#ifndef __PI_TEST_H
#define __PI_TEST_H

#include <stdio.h>
#include <stdlib.h>

struct piS                  //struct for threading
{
    int threads;  //amount of threads running
    int iterations;  //amount of iterations  
    int operation;  //whether to add or subtract
    double total;   //value of pi
};

double calcPi(int numIter);
void *piPthreads(void *info);

#endif

(pi.c) Как я помещаю значения в структуру и вычисляю pi

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <pthread.h>
#include "pi.h"

/***************************************************
 * struct for pthreads
***************************************************/

void *piPthreads(void *arg)
{
    struct piS *threader = (struct piS*) arg;
    int operation = threader->operation;    //rank
    int threads = threader->threads;    //count
    int iterations = threader->iterations / threads;
    double begin = operation * iterations;
    double end = begin + iterations;
    printf("iterations = %d\n",iterations);
    threader->total = 0;
    int plusMinus = 1;

    if((int)begin%2)
        plusMinus = -1;

    double loop = begin;

    printf("begin: %d, end: %d\n",begin, end);

    for(loop = begin;loop < end;loop++)
    {
        if(plusMinus == 1)
        {
            threader->total += (1/(2*loop+1));
            printf("threader->total = %d\n",threader->total);
        }
        else
            {
                threader->total -= (1/(2*loop+1));
                printf("threader->total = %d\n",threader->total);
            }
        } 

        return NULL;
    }

(pithreadDriver.c) Как я запускаю pthread и как он обрабатывается

//driver class to run pthread
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "pi.h"


/**********************************************
* main()
* handles command line arguments and passes
* for pThreads
**********************************************/
int main(int argc, char** argv){

    int numIter = 100;
    int pthread = 4;


    //Handle command line args
    if(argc != 3)
    {
        printf("Default:Number of threads being set to 4.\n");
        printf("Default:Number of iterations set to 100.\n");

        if(atoi(argv[2]) > 28)
        {
            printf("Default:Number of threads being set to 4\n");
            printf("Max threads possible 28\n");
            pthread = 4;

        }
            printf("Format for running:( executable   iterations    threads)\n");
    }

    if(argc == 3)
    {
        //Assign args
        numIter = atoi(argv[1]);

        //Assign threads
        pthread = atoi(argv[2]);
    }       

    //creating and handling pthreads
    pthread_t *tids = (pthread_t*) malloc(sizeof(pthread_t) * pthread);

    struct piS *threader = (struct piS*) malloc(sizeof(struct piS) * pthread);

    int loop = 0;


    //filling in values for pthreads and creating each thread
    for(loop = 0;loop < pthread;loop++)
    {
        threader[loop].operation = loop;
        threader[loop].threads = pthread;
        threader[loop].iterations = numIter;
        printf("threader[%d].iterations = %d\n",loop,threader[loop].iterations);
        pthread_create(&tids[loop],NULL,piPthreads,&threader);
    }

     double answer = 0;

    for(loop = 0;loop < pthread; loop++)
    {
        pthread_join(tids[loop],NULL);
        answer += threader[loop].total;
        printf("threader[%d] = %d\n",loop,threader[loop].total);
    }

    answer = answer * 4;

    printf("answer is %f using %d iterations\n",answer,numIter);            

    return 0;
}

(out.txt) Вывод при его запуске

Default:Number of threads being set to 4.
Default:Number of iterations set to 100.
Format for running:( executable   iterations    threads)
threader[0].iterations = 100
threader[1].iterations = 100
threader[2].iterations = 100
iterations = 0
begin: 0, end: 0
threader[3].iterations = 100
iterations = 0
begin: 0, end: 0
threader[0] = 0
threader[1] = 1
iterations = 0
begin: 0, end: 0
iterations = 0
begin: 0, end: 0
threader[2] = 2
threader[3] = 3
answer is 0.000000 using 100 iterations

Я вижу, что потокиработает правильно.Я также понимаю, почему в моем цикле for не учитываются фактические расчеты.Большая часть этого кода - код, который нам показал инструктор, и он был действительно затронут, но не пересмотрен.Я попытался использовать операторы print внутри моего pi.c, чтобы выяснить это.Я вижу, что значение итерации не помещается правильно.Из того, что я получил из этого кода, он не будет работать так, как я хочу, чтобы он работал.Но у меня проблемы с выяснением, почему мои итерации не проходят.

1 Ответ

0 голосов
/ 21 сентября 2018

Четвертый параметр, который вы передаете pthread_create, равен &threader.Это выражение имеет тип struct piS **, поскольку threader имеет тип struct piS *.Но в вашей функции потока вы конвертируете параметр в тип struct piS *.Они не совпадают, поэтому вы пытаетесь обработать объект одного типа как объект другого типа.Это вызывает неопределенное поведение .

Вы должны передать &threader[loop] в pthread_create, чтобы типы соответствовали.

pthread_create(&tids[loop],NULL,piPthreads,&threader[loop]);
...