用c/c++进行多线程编程:读者-写者问题。 1.设置两类线程,一类为读者,一类为写者; 2.使用菜单随机启动读者或写者; 3.在窗口上显示读者或写者执行状态; 4.随着线程的执行,更新窗口的显示分析
时间: 2024-04-30 08:19:36 浏览: 81
下面是一份基于 Windows API 的 C++ 代码实现:
```c++
#include <iostream>
#include <windows.h>
#include <ctime>
using namespace std;
// 读写锁
CRITICAL_SECTION cs_read;
CRITICAL_SECTION cs_write;
// 读写计数器
int read_count = 0;
bool is_writing = false;
// 读者线程
DWORD WINAPI ReaderThread(LPVOID lpParam)
{
while (true)
{
// 等待 1-5 秒
Sleep((rand() % 5 + 1) * 1000);
// 加读锁
EnterCriticalSection(&cs_read);
read_count++;
if (read_count == 1)
{
// 如果是第一个读者,需要加写锁
EnterCriticalSection(&cs_write);
is_writing = true;
}
LeaveCriticalSection(&cs_read);
// 输出状态
cout << "Reader is reading..." << endl;
// 等待 1-5 秒
Sleep((rand() % 5 + 1) * 1000);
// 解读锁
EnterCriticalSection(&cs_read);
read_count--;
if (read_count == 0)
{
// 如果是最后一个读者,需要解写锁
LeaveCriticalSection(&cs_write);
is_writing = false;
}
LeaveCriticalSection(&cs_read);
}
return 0;
}
// 写者线程
DWORD WINAPI WriterThread(LPVOID lpParam)
{
while (true)
{
// 等待 1-5 秒
Sleep((rand() % 5 + 1) * 1000);
// 加写锁
EnterCriticalSection(&cs_write);
is_writing = true;
// 输出状态
cout << "Writer is writing..." << endl;
// 等待 1-5 秒
Sleep((rand() % 5 + 1) * 1000);
// 解写锁
LeaveCriticalSection(&cs_write);
is_writing = false;
}
return 0;
}
int main()
{
// 初始化随机数种子
srand((unsigned int)time(NULL));
// 初始化读写锁
InitializeCriticalSection(&cs_read);
InitializeCriticalSection(&cs_write);
while (true)
{
char choice;
cout << "Press 'r' to start reader thread, 'w' to start writer thread: ";
cin >> choice;
if (choice == 'r')
{
// 创建读者线程
HANDLE hReaderThread = CreateThread(NULL, 0, ReaderThread, NULL, 0, NULL);
if (hReaderThread == NULL)
{
cout << "Failed to create reader thread." << endl;
return 1;
}
CloseHandle(hReaderThread);
}
else if (choice == 'w')
{
// 创建写者线程
HANDLE hWriterThread = CreateThread(NULL, 0, WriterThread, NULL, 0, NULL);
if (hWriterThread == NULL)
{
cout << "Failed to create writer thread." << endl;
return 1;
}
CloseHandle(hWriterThread);
}
else
{
cout << "Invalid choice." << endl;
}
// 输出当前状态
if (is_writing)
{
cout << "Writer is writing." << endl;
}
else if (read_count > 0)
{
cout << "Readers are reading." << endl;
}
else
{
cout << "No readers or writers." << endl;
}
}
// 销毁读写锁
DeleteCriticalSection(&cs_read);
DeleteCriticalSection(&cs_write);
return 0;
}
```
这个程序使用了 Windows API 中的 CRITICAL_SECTION 实现了读写锁。读者和写者线程分别在加锁和解锁的时候,需要对读写计数器进行操作,以实现多个读者和单个写者的限制。在主线程中,使用一个简单的菜单让用户选择启动读者或写者线程,同时输出当前的执行状态。
阅读全文