我想使用线程在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);
}
该d
数组可以容纳10个值,因此,如果N
大于10,则存在超出范围的问题:
int d[10] = {0};
...
for (i=0; i<N; i++)
{
d[i] = i; // if i > 10 => you access out of bounds => problem
您对其他阵列也有同样的问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句