#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#define NUM_THREADS 4
int arraySum = 0;
int array[] = {20, 18, 16, 14, 12, 10, 8, 6, 4, 2, -10, -20, -30, -40, 15, 23, 25, 75, 45, 33};
int low = 0;
int high = 4;
// Function that calculates sum of 5 elements of an array
void *ArraySum(void *threadid)
{
// Iterating from index low to high
for(int i = low; i < high; i++)
{
// Accumulating array sum
arraySum = arraySum + array[i];
}
// Updating lowest and highest index
low = low + 5;
high = high + 5;
// Exiting current thread
pthread_exit(NULL);
}
// Main function
int main(int argc, char *argv[])
{
int rc, t;
// Creating thread array
pthread_t threads[NUM_THREADS];
// Iterating over each thread
for(t = 0; t < NUM_THREADS; t++)
{
// Creating a thread
rc = pthread_create(&threads[t], NULL, ArraySum, &t);
// Checking for status
if(rc)
{
printf(" Error; return code from pthread_create() is %d \n", rc);
exit(-1);
}
}
/* Waiting till all threads finish their execution */
for (t = 0; t < NUM_THREADS; t++)
{
pthread_join(threads[t], NULL);
}
// Printing Array sum
printf("\nArray Sum: %d \n", arraySum);
pthread_exit(NULL);
}
目标是创建 4 个不同的线程并将数组中的所有数字相加。例如,第一个线程将前 5 个数字相加 (20 + 18 + 16 + 14 + 12)。第二个线程将添加接下来的 5 个,依此类推。
当我运行它时,我得到的总数是 164,但我预计是 211。我相信我已经创建了 4 个不同的线程并正确连接了它们,但输出是错误的。
最佳答案
这里我写了将不同线程求和在一起的解决方案。我基本上使用线程 ID 来确定每个线程的开始/结束索引。因此,每个线程计算部分和,因此不需要同步。当一个线程退出时,他的部分和被返回并累加到最终的和中。
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#define NUM_THREADS 4
int array[] = {20, 18, 16, 14, 12, 10, 8, 6, 4, 2, -10, -20, -30, -40, 15, 23, 25, 75, 45, 33};
// Function that calculates sum of 5 elements of an array
void *ArraySum(void *arg)
{
int id = (int)arg;
int partial_sum = 0;
int begin = id * (NUM_THREADS + 1);
int end = id * (NUM_THREADS + 1) + NUM_THREADS;
// Iterating from index low to high
for(int i = begin; i <= end; i++)
{
// Accumulating array partial sum
partial_sum += array[i];
}
// Exiting current thread
pthread_exit((void *)partial_sum);
}
// Main function
int main(int argc, char *argv[])
{
int rc, t;
int arraySum = 0;
void *retvalue;
// Creating thread array
pthread_t threads[NUM_THREADS];
// Iterating over each thread
for(t = 0; t < NUM_THREADS; t++)
{
// Creating a thread
rc = pthread_create(&threads[t], NULL, ArraySum, (void *)t);
// Checking for status
if(rc)
{
printf(" Error; return code from pthread_create() is %d \n", rc);
exit(-1);
}
}
/* Waiting till all threads finish their execution */
for (t = 0; t < NUM_THREADS; t++)
{
pthread_join(threads[t], &retvalue);
arraySum += (int)retvalue;
}
// Printing Array sum
printf("\nArray Sum: %d \n", arraySum);
pthread_exit(NULL);
}
关于c - 在 C 中将不同的线程汇总在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44102746/