本关任务:程序 3.c 使用 2 个线程计算从 1 到 200 的累加和,请将其改为用 3 个线
时间: 2023-11-09 15:02:37 浏览: 170
本关任务是将程序3.c中使用2个线程计算从1到200的累加和改为使用3个线程进行计算。
要实现这一目标,我们需要对原来的程序进行适当修改。具体的修改方法如下:
1. 首先,我们需要在程序中增加一个额外的线程,即将原来只有2个线程的计算方式改为3个线程。
2. 将原有的循环“for (i = 1; i <= 100; i++)”修改为“for (i = 1; i <= 67; i++)”。这样可以保证每个线程都能处理到100个数字的累加和。
3. 改变线程的创建和执行的逻辑,使得其中一个线程计算1到67的累加和,另一个线程计算68到134的累加和,第三个线程计算135到200的累加和。
4. 需要在主线程中等待所有线程结束后,计算出三个子线程的累加和的和。
修改完成后的程序运行逻辑如下:
1. 创建3个线程,每个线程对应一个不同的累加和计算范围。
2. 线程1计算1到67的累加和,线程2计算68到134的累加和,线程3计算135到200的累加和。
3. 主线程等待所有子线程结束。
4. 计算三个子线程的累加和的和,并输出结果。
通过以上的修改,即可实现将原来使用2个线程计算的累加和改为使用3个线程进行计算的目标。
这种修改方式保证了每个线程都处理到一定数量的数字,并且在所有线程都结束后,主线程将这些线程的计算结果相加得到最终的累加和。
相关问题
本关任务:程序 3.c 使用 2 个线程计算从 1 到 200 的累加和,请将其改为用 3 个线程实现, 3 个线程分别完成函数 p1、p2 和 p3 的计算任务,总体功能不变。
```c
#include <stdio.h>
#include <pthread.h>
#define N 200
int sum = 0;
pthread_mutex_t mutex;
void *p1(void *arg) {
int i;
for (i = 1; i <= N / 3; i++) {
pthread_mutex_lock(&mutex);
sum += i;
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void *p2(void *arg) {
int i;
for (i = N / 3 + 1; i <= N * 2 / 3; i++) {
pthread_mutex_lock(&mutex);
sum += i;
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void *p3(void *arg) {
int i;
for (i = N * 2 / 3 + 1; i <= N; i++) {
pthread_mutex_lock(&mutex);
sum += i;
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main() {
pthread_t t1, t2, t3;
pthread_mutex_init(&mutex, NULL);
pthread_create(&t1, NULL, p1, NULL);
pthread_create(&t2, NULL, p2, NULL);
pthread_create(&t3, NULL, p3, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_join(t3, NULL);
pthread_mutex_destroy(&mutex);
printf("sum = %d\n", sum);
return 0;
}
```
给出代码关于多线程编程实现:程序 3.c 使用 2 个线程计算从 1 到 200 的累加和,请将其改为用 3 个线程实现, 3 个线程分别完成函数 p1、p2 和 p3 的计算任务,总体功能不变
以下是修改后的代码:
```c
#include <stdio.h>
#include <pthread.h>
int sum = 0; // 全局变量,存储累加和
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 互斥锁
// 线程一计算任务
void *p1(void *arg) {
int i;
for (i = 1; i <= 100; i++) {
pthread_mutex_lock(&mutex);
sum += i;
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
// 线程二计算任务
void *p2(void *arg) {
int i;
for (i = 101; i <= 200; i++) {
pthread_mutex_lock(&mutex);
sum += i;
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
// 线程三计算任务
void *p3(void *arg) {
int i;
for (i = 201; i <= 300; i++) {
pthread_mutex_lock(&mutex);
sum += i;
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main() {
pthread_t tid1, tid2, tid3; // 线程 ID
pthread_create(&tid1, NULL, p1, NULL); // 创建线程一
pthread_create(&tid2, NULL, p2, NULL); // 创建线程二
pthread_create(&tid3, NULL, p3, NULL); // 创建线程三
pthread_join(tid1, NULL); // 等待线程一结束
pthread_join(tid2, NULL); // 等待线程二结束
pthread_join(tid3, NULL); // 等待线程三结束
printf("1+2+...+300=%d\n", sum); // 输出结果
return 0;
}
```
在原有的基础上,新增了 `p3` 函数用于计算 201 到 300 的累加和,同时在 `main` 函数中新增了创建和等待线程三的代码。由于全局变量 `sum` 可能会被多个线程同时修改,因此需要使用互斥锁来保证线程安全。