(3) 实现进程池计算素数:编写一个程序primer_pro3.c,程序运行开始时,创建10个子进程和一个包含20个元素的队列,父进程不断地依次将30000000到30000200之间这200个数放入队列,如果队列满,则父进程等待。 队列的定义可参考如下: #define MAXSIZE 20 struct quequ_st{ int finished; //父进程是否已将所有200个整数放入了队列 int head; //队列头
时间: 2024-03-12 07:46:13 浏览: 38
下面是一个实现进程池计算素数的程序primer_pro3.c,包含10个子进程和一个20个元素的队列:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pthread.h>
#define MAXSIZE 20
struct queue_st{
int finished; // 父进程是否已将所有200个整数放入了队列
int head; // 队列头
int tail; // 队列尾
int data[MAXSIZE]; // 队列数据
};
void *worker(void *arg);
int main(int argc, char *argv[])
{
struct queue_st queue = {0, 0, 0};
pthread_t workers[10];
int i;
for (i = 0; i < 10; i++) {
if (pthread_create(&workers[i], NULL, worker, &queue) != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
}
for (i = 30000000; i < 30000200; i++) {
while ((queue.tail + 1) % MAXSIZE == queue.head) {
sleep(1);
}
queue.data[queue.tail] = i;
queue.tail = (queue.tail + 1) % MAXSIZE;
}
queue.finished = 1;
for (i = 0; i < 10; i++) {
pthread_join(workers[i], NULL);
}
return 0;
}
void *worker(void *arg)
{
struct queue_st *queue = (struct queue_st *) arg;
int n, i, is_prime;
while (1) {
while (queue->head == queue->tail) {
if (queue->finished) {
return NULL;
}
sleep(1);
}
n = queue->data[queue->head];
queue->head = (queue->head + 1) % MAXSIZE;
is_prime = 1;
for (i = 2; i <= n / 2; i++) {
if (n % i == 0) {
is_prime = 0;
break;
}
}
if (is_prime) {
printf("%d is prime\n", n);
}
}
}
```
程序的主要思路是:父进程不断地将30000000到30000200之间这200个数放入队列,如果队列满,则父进程等待。每个子进程从队列中取出一个数,判断该数是否是素数,并输出结果。如果队列为空,则子进程等待。
程序中使用了一个结构体queue_st来表示队列,其中包含了队列的状态信息和数据。每个子进程调用worker函数来进行计算,函数中使用while循环不断地从队列中取出数进行计算。
在主函数中,程序创建了10个子进程,并不断地将30000000到30000200之间这200个数放入队列,直到所有数都被放入队列中。当父进程将所有数都放入队列后,设置finished标志为1,通知子进程结束计算。
子进程在计算过程中,如果发现队列为空,则等待1秒钟后再次尝试取数。如果发现finished标志为1,则表示父进程已经将所有数都放入队列了,子进程应该退出计算。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)