写一段c语言代码,利用多线程进行区间分隔求解
时间: 2024-05-26 13:11:09 浏览: 8
以下是示例代码:
#include <stdio.h>
#include <pthread.h>
// 定义线程参数结构体
struct ThreadArgs {
int start;
int end;
int sum;
};
// 线程函数
void* threadFunc(void* arg) {
struct ThreadArgs* threadArgs = (struct ThreadArgs*)arg;
int start = threadArgs->start;
int end = threadArgs->end;
int sum = 0;
for (int i = start; i <= end; i++) {
sum += i;
}
threadArgs->sum = sum;
return NULL;
}
int main() {
int nThreads = 4;
int n = 100;
int segmentSize = (n + nThreads - 1) / nThreads;
pthread_t threads[nThreads];
struct ThreadArgs threadArgs[nThreads];
int sum = 0;
// 创建线程并执行
for (int i = 0; i < nThreads; i++) {
threadArgs[i].start = i * segmentSize + 1;
threadArgs[i].end = (i + 1) * segmentSize;
if (threadArgs[i].end > n) {
threadArgs[i].end = n;
}
pthread_create(&threads[i], NULL, threadFunc, &threadArgs[i]);
}
// 等待线程执行结束,并计算总和
for (int i = 0; i < nThreads; i++) {
pthread_join(threads[i], NULL);
sum += threadArgs[i].sum;
}
printf("Sum is %d\n", sum);
return 0;
}
以上代码实现了将整数区间1-100分成4个子区间,在4个线程中分别计算每个子区间内整数的总和,最终将所有子区间的总和相加,输出结果。注意,在实际使用时需要根据具体情况进行修改。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)