如何在C中拥有动态数量的线程

时间:2016-12-16 09:44:49

标签: c multithreading pthreads

我想用c来计算c中的数学求和。 (Σx^ i,从0到N)每个线程应该计算求和的每个项,最后在主程序中,程序应该将它们全部相加并打印出来。 我应该如何动态地创建线程数? 这是我的代码:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <math.h>

pthread_t sadaf[10];
int i,a[10];
long int x,N;
int sum=0;
pthread_mutex_t mtx;

void *Myfun(void *tid)
{
    int *ThreadID=(int *)tid;
    pthread_mutex_lock(&mtx);
    printf("The thread with id of %d calculated x^i\n",*ThreadID);
    a[*ThreadID]=pow(x,*ThreadID);
    sum=sum+a[*ThreadID];
    pthread_mutex_unlock(&mtx);

}

int main()
{
     int d[10] = {0};
     printf("->**************************************************************************<-\n");
     printf("This program will calculate the following function:\n-> ∑x^i ,From 0 to N \n");
     printf("->**************************************************************************<-\n");
     printf("Please enter x:\n");
     scanf("%ld",&x);
     printf("Please enter N:\n");
     scanf("%ld",&N);

    for (i=0; i<N; i++)
    {
        d[i] = i;
        pthread_create(&sadaf[i],NULL,Myfun,(void *)&d[i]);
    }
    for (i=0; i<N; i++)
    {
        pthread_join(sadaf[i],NULL);
    }


    printf("The sum is: %d\n",sum);

}

2 个答案:

答案 0 :(得分:0)

您在开头只定义了10个iframe

pthreads

创建超过10个线程将导致未定义的行为。

答案 1 :(得分:0)

/usr/lib/postgresql/9.4/bin/pg_restore --host 'localhost' --port 5432 --schema="schema1" --table="table1" --username "postgres" --dbname "DB4TEST" --no-password --verbose "/path/to/fullDB.backup" 数组可以包含10个值,因此如果d大于10,则会出现问题:

N

您也遇到与其他阵列相同的问题。