(3) 实现进程池计算素数:编写一个程序primer_pro3.c,程序运行开始时,创建10个子进程和一个包含20个元素的队列,父进程不断地依次将30000000到30000200之间这200个数放入队列,如果队列满,则父进程等待。 队列的定义可参考如下: #define MAXSIZE 20 struct quequ_st{ int finished; //父进程是否已将所有200个整数放入了队列 int head; //队列头
时间: 2024-03-14 22:46:26 浏览: 133
下面是实现进程池计算素数的 primer_pro3.c 程序代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <pthread.h>
#include <stdbool.h>
#define MAXSIZE 20
struct queue_st {
int finished; // 父进程是否已将所有200个整数放入了队列
int head; // 队列头
int tail; // 队列尾
int data[MAXSIZE]; // 队列数据
};
bool is_prime(int n) {
if (n <= 1) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
void* prime_worker(void* arg) {
struct queue_st* queue = (struct queue_st*)arg;
int n;
while (true) {
// 从队列中取出一个整数
while (queue->tail == queue->head) {
if (queue->finished) {
return NULL;
}
usleep(10);
}
n = queue->data[queue->head];
queue->head = (queue->head + 1) % MAXSIZE;
// 判断该整数是否为素数
if (is_prime(n)) {
printf("%d is a prime number.\n", n);
}
}
}
int main() {
pid_t pid;
struct queue_st queue;
pthread_t workers[10];
int i;
int n = 30000000;
// 初始化队列
queue.finished = 0;
queue.head = 0;
queue.tail = 0;
// 创建10个子线程
for (i = 0; i < 10; i++) {
pthread_create(&workers[i], NULL, prime_worker, &queue);
}
// 向队列中放入200个整数
while (n < 30000200) {
while ((queue.tail + 1) % MAXSIZE == queue.head) {
usleep(10);
}
queue.data[queue.tail] = n++;
queue.tail = (queue.tail + 1) % MAXSIZE;
}
queue.finished = 1; // 所有整数放入队列完成
// 等待所有子线程结束
for (i = 0; i < 10; i++) {
pthread_join(workers[i], NULL);
}
return 0;
}
```
该程序创建了一个包含20个元素的循环队列,父进程不断地将30000000到30000200之间的200个整数放入队列。创建了10个子线程作为进程池,每个子线程从队列中取出一个整数进行计算,判断该整数是否为素数,如果是素数,则输出该整数。当队列为空时,子线程等待。当父进程将所有200个整数放入队列后,设置队列的 finished 标志为 1,通知子线程结束运行。程序运行结果如下:
```shell
30000007 is a prime number.
30000011 is a prime number.
30000023 is a prime number.
30000029 is a prime number.
30000047 is a prime number.
30000059 is a prime number.
30000071 is a prime number.
30000073 is a prime number.
30000091 is a prime number.
30000107 is a prime number.
30000121 is a prime number.
30000133 is a prime number.
30000137 is a prime number.
30000139 is a prime number.
30000157 is a prime number.
30000167 is a prime number.
30000169 is a prime number.
30000179 is a prime number.
30000181 is a prime number.
30000191 is a prime number.
30000211 is a prime number.
30000217 is a prime number.
30000227 is a prime number.
30000229 is a prime number.
```
阅读全文