进程的同步与互斥实验代码
时间: 2023-10-10 11:15:43 浏览: 91
好的,以下是一个简单的进程同步和互斥的实验代码,供参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE]; // 共享缓存区
int in = 0, out = 0; // 生产者和消费者的指针
pthread_mutex_t mutex; // 互斥锁
sem_t empty, full; // 空缓存区和满缓存区信号量
void *producer(void *arg) {
int item = 1;
while (1) {
sleep(1); // 生产者生产一个产品需要1秒钟
sem_wait(&empty); // 等待空缓存区信号量
pthread_mutex_lock(&mutex); // 加锁
buffer[in] = item;
printf("Producer produce item %d, in = %d\n", item, in);
in = (in + 1) % BUFFER_SIZE;
item++;
pthread_mutex_unlock(&mutex); // 解锁
sem_post(&full); // 发送满缓存区信号量
}
}
void *consumer(void *arg) {
int item;
while (1) {
sem_wait(&full); // 等待满缓存区信号量
pthread_mutex_lock(&mutex); // 加锁
item = buffer[out];
printf("Consumer consume item %d, out = %d\n", item, out);
out = (out + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex); // 解锁
sem_post(&empty); // 发送空缓存区信号量
}
}
int main() {
pthread_t p, c;
pthread_mutex_init(&mutex, NULL);
sem_init(&empty, 0, BUFFER_SIZE); // 初始化空缓存区信号量
sem_init(&full, 0, 0); // 初始化满缓存区信号量
pthread_create(&p, NULL, producer, NULL);
pthread_create(&c, NULL, consumer, NULL);
pthread_join(p, NULL);
pthread_join(c, NULL);
pthread_mutex_destroy(&mutex);
sem_destroy(&empty);
sem_destroy(&full);
return 0;
}
```
在这个代码中,我们使用了互斥锁(`pthread_mutex_t`)和信号量(`sem_t`)来实现进程同步和互斥。生产者和消费者进程通过互斥锁来访问共享缓存区,通过信号量来实现进程同步。
在主函数中,我们首先初始化互斥锁和信号量,然后创建生产者和消费者进程,并等待它们结束。最后,我们释放互斥锁和信号量。
希望这个简单的代码能够帮助你更好地理解进程同步和互斥的实现。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)