使用信号量机制实现:进程A 和B共享浮点数组data[1000], 它们共同完成对data中浮点数 据的累加计算,由进程A输出 最终结果
时间: 2023-05-29 11:02:27 浏览: 109
利用信号量实现进程间同步
下面是使用信号量机制实现进程A和B共享浮点数组data[1000]的代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/sem.h>
#define SEM_MUTEX 0
#define SEM_FULL 1
union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
};
int semid;
float data[1000];
void init_semaphores() {
union semun arg;
unsigned short values[2] = {1, 0}; // binary semaphores
arg.array = values;
if ((semid = semget(IPC_PRIVATE, 2, 0666 | IPC_CREAT)) == -1) {
perror("semget");
exit(1);
}
semctl(semid, 0, SETALL, arg);
}
void remove_semaphores() {
if (semctl(semid, 0, IPC_RMID, NULL) == -1) {
perror("semctl");
exit(1);
}
}
void wait_semaphore(int semindex) {
struct sembuf sb;
sb.sem_num = semindex;
sb.sem_op = -1;
sb.sem_flg = SEM_UNDO;
if (semop(semid, &sb, 1) == -1) {
perror("semop");
exit(1);
}
}
void signal_semaphore(int semindex) {
struct sembuf sb;
sb.sem_num = semindex;
sb.sem_op = 1;
sb.sem_flg = SEM_UNDO;
if (semop(semid, &sb, 1) == -1) {
perror("semop");
exit(1);
}
}
void process_A() {
int i;
float sum = 0.0;
for (i = 0; i < 1000; i++) {
wait_semaphore(SEM_MUTEX); // acquire the mutex semaphore
data[i] += 1.0; // increment the data array element
sum += data[i]; // accumulate the sum
signal_semaphore(SEM_MUTEX); // release the mutex semaphore
}
printf("Process A result: %f\n", sum);
}
void process_B() {
int i;
for (i = 0; i < 1000; i++) {
wait_semaphore(SEM_MUTEX); // acquire the mutex semaphore
data[i] += 2.0; // increment the data array element
signal_semaphore(SEM_FULL); // release the full semaphore
signal_semaphore(SEM_MUTEX); // release the mutex semaphore
}
}
int main() {
init_semaphores();
pid_t pid;
if ((pid = fork()) == -1) {
perror("fork");
exit(1);
} else if (pid == 0) { // child process B
process_B();
} else { // parent process A
process_A();
wait(NULL);
remove_semaphores();
}
return 0;
}
```
本例中使用了两个二进制信号量:一个表示互斥(SEMAPHORE_MUTEX),另一个表示缓存区是否已满(SEMAPHORE_FULL)。
进程A和B均可以访问data[]数组。进程A对数组进行累加计算,并输出最终结果;进程B对数组进行累加,每次累加完成后发送一个缓存区已满信号,通知进程A可对数组进行处理。信号量机制确保了进程A和B之间对data[]数组的访问顺序。
阅读全文