C语言实现时间片轮转和生产者消费者问题结合
时间: 2024-02-19 18:59:18 浏览: 20
时间片轮转是一种常见的进程调度算法,可以让多个进程轮流使用CPU并实现公平调度。生产者消费者问题是一种常见的同步问题,其中生产者进程生产数据,消费者进程消费数据,需要保证生产者和消费者之间的同步和互斥。下面是时间片轮转和生产者消费者问题结合的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#define BUFFER_SIZE 10
#define MAX_TIME_SLICE 10
#define PRODUCER_NUM 2
#define CONSUMER_NUM 2
int buffer[BUFFER_SIZE];
int in = 0, out = 0, count = 0;
int time_slice = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t full = PTHREAD_COND_INITIALIZER;
pthread_cond_t empty = PTHREAD_COND_INITIALIZER;
void *producer(void *arg)
{
int id = *(int*)arg;
while (1) {
pthread_mutex_lock(&mutex);
while (count == BUFFER_SIZE) {
pthread_cond_wait(&empty, &mutex);
}
int item = rand() % 100;
buffer[in] = item;
printf("Producer %d produced item %d\n", id, item);
in = (in + 1) % BUFFER_SIZE;
count++;
pthread_cond_signal(&full);
pthread_mutex_unlock(&mutex);
usleep((rand() % 100) * 1000); // 模拟生产时间
}
}
void *consumer(void *arg)
{
int id = *(int*)arg;
while (1) {
pthread_mutex_lock(&mutex);
while (count == 0) {
pthread_cond_wait(&full, &mutex);
}
int item = buffer[out];
printf("Consumer %d consumed item %d\n", id, item);
out = (out + 1) % BUFFER_SIZE;
count--;
pthread_cond_signal(&empty);
pthread_mutex_unlock(&mutex);
usleep((rand() % 100) * 1000); // 模拟消费时间
}
}
void *scheduler(void *arg)
{
int i;
while (1) {
if (count == 0) {
usleep(1000); // 如果缓冲区为空,等待一段时间
continue;
}
pthread_mutex_lock(&mutex);
// 选择需要执行的进程
int round_robin = time_slice % PRODUCER_NUM;
for (i = 0; i < CONSUMER_NUM; i++) {
int index = (round_robin + i) % CONSUMER_NUM;
if (count > 0) {
printf("Scheduler selected Consumer %d\n", index);
round_robin = (index + 1) % PRODUCER_NUM;
pthread_mutex_unlock(&mutex);
usleep(MAX_TIME_SLICE * 1000); // 执行一定时间片
time_slice += MAX_TIME_SLICE;
pthread_mutex_lock(&mutex);
break;
}
}
pthread_mutex_unlock(&mutex);
}
}
int main()
{
int i, ret;
pthread_t pid[PRODUCER_NUM], cid[CONSUMER_NUM], sid;
srand(time(NULL));
for (i = 0; i < PRODUCER_NUM; i++) {
int *id = (int*)malloc(sizeof(int));
*id = i;
ret = pthread_create(&pid[i], NULL, producer, id);
if (ret != 0) {
printf("Producer %d create error!\n", i);
return -1;
}
}
for (i = 0; i < CONSUMER_NUM; i++) {
int *id = (int*)malloc(sizeof(int));
*id = i;
ret = pthread_create(&cid[i], NULL, consumer, id);
if (ret != 0) {
printf("Consumer %d create error!\n", i);
return -1;
}
}
ret = pthread_create(&sid, NULL, scheduler, NULL);
if (ret != 0) {
printf("Scheduler create error!\n");
return -1;
}
pthread_join(sid, NULL);
return 0;
}
```
上述代码中,生产者和消费者线程不断地生产和消费数据,通过互斥锁和条件变量实现同步和互斥。调度器线程通过时间片轮转算法选择需要执行的进程,并在执行完一定时间片后切换到下一个进程。整个程序实现了生产者消费者问题的同步和时间片轮转的公平调度。