我有一个程序要求用户输入(数字= n
)。然后创建一个线程来计算从1到n
的总和。我现在想要创建其他线程以向用户输入数字n
添加数字。然后,第二个线程计算1到n+1
的总和,然后第三个线程将计算1到n+2
的总和。
# include <stdio.h>
# include <pthread.h>
void * thread_calc(void *);
int TotalSum=0;
int main()
{
int iNumber;
pthread_t tid, tid2;
printf("Enter Number Up to Which You want to Sum :");
scanf("%d",&iNumber);
pthread_create(&tid,NULL,thread_calc,(void *) &iNumber);
//pthread_create(&tid2,NULL,thread_calc,(void *)(&iNumber+1));
pthread_join(tid,NULL);
pthread_join(tid2,NULL);
printf("Thread %d running, Final Sum is : %d \n", tid,TotalSum);
pthread_create(&tid2,NULL,thread_calc,(void *) &iNumber+1);
pthread_join(tid,NULL);
printf("Thread %d running, Final Sum is : %d \n", tid2,TotalSum);
// return 0;
}
void *thread_calc(void *num)
{
int *iNumber;
iNumber=(int*)num;
TotalSum = ((*iNumber + 1)* (*iNumber))/2;
pthread_exit(NULL);
}