使用C语言实现Windows生产者消费者问题的问题。
时间: 2024-05-10 10:14:11 浏览: 90
基于 C语言 生产者消费者问题【100010806】
生产者消费者问题是一个经典的同步问题,用于描述多个线程之间的生产和消费关系。在Windows操作系统中,可以使用Windows API提供的信号量机制来实现生产者消费者问题的解决方案。
下面是一个使用C语言实现Windows生产者消费者问题的示例代码:
```c
#include <windows.h>
#include <stdio.h>
#define BUFFER_SIZE 10
#define PRODUCER_LOOP 100
#define CONSUMER_LOOP 100
int buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
int count = 0;
HANDLE hSemEmpty, hSemFull, hMutex;
DWORD WINAPI producer(LPVOID lpParam) {
int i, data;
for (i = 0; i < PRODUCER_LOOP; i++) {
data = i;
WaitForSingleObject(hSemEmpty, INFINITE);
WaitForSingleObject(hMutex, INFINITE);
buffer[in] = data;
in = (in + 1) % BUFFER_SIZE;
count++;
printf("Producer %d produced data %d\n", GetCurrentThreadId(), data);
ReleaseMutex(hMutex);
ReleaseSemaphore(hSemFull, 1, NULL);
}
return 0;
}
DWORD WINAPI consumer(LPVOID lpParam) {
int i, data;
for (i = 0; i < CONSUMER_LOOP; i++) {
WaitForSingleObject(hSemFull, INFINITE);
WaitForSingleObject(hMutex, INFINITE);
data = buffer[out];
out = (out + 1) % BUFFER_SIZE;
count--;
printf("Consumer %d consumed data %d\n", GetCurrentThreadId(), data);
ReleaseMutex(hMutex);
ReleaseSemaphore(hSemEmpty, 1, NULL);
}
return 0;
}
int main() {
HANDLE hProducer[2], hConsumer[2];
DWORD producerId[2], consumerId[2];
hSemEmpty = CreateSemaphore(NULL, BUFFER_SIZE, BUFFER_SIZE, NULL);
hSemFull = CreateSemaphore(NULL, 0, BUFFER_SIZE, NULL);
hMutex = CreateMutex(NULL, FALSE, NULL);
hProducer[0] = CreateThread(NULL, 0, producer, NULL, 0, &producerId[0]);
hProducer[1] = CreateThread(NULL, 0, producer, NULL, 0, &producerId[1]);
hConsumer[0] = CreateThread(NULL, 0, consumer, NULL, 0, &consumerId[0]);
hConsumer[1] = CreateThread(NULL, 0, consumer, NULL, 0, &consumerId[1]);
WaitForMultipleObjects(4, hProducer, TRUE, INFINITE);
WaitForMultipleObjects(2, hConsumer, TRUE, INFINITE);
CloseHandle(hSemEmpty);
CloseHandle(hSemFull);
CloseHandle(hMutex);
return 0;
}
```
在这个例子中,定义了一个大小为10的缓冲区,两个生产者线程和两个消费者线程。生产者线程循环100次,每次产生一个数据并将其存入缓冲区,消费者线程循环100次,每次从缓冲区中取出一个数据进行消费。
使用Windows API提供的CreateSemaphore、WaitForSingleObject和ReleaseSemaphore函数实现信号量机制,使用CreateMutex函数实现互斥锁机制。
需要注意的是,在生产者和消费者线程中使用WaitForSingleObject和ReleaseSemaphore函数需要注意顺序,不然会导致线程死锁或者数据混乱的情况。
阅读全文