项目新建
在VS2013里面新建一个Qt的控制台应用程序,添加main.cpp
定义两个信号量
#include <QObject>
#include <QtCore/QCoreApplication>
#include <QSemaphore>
#include <QThread>
#include <iostream>
const int gDataSize = 100000;// 总数据量
const int gBufferSize = 5000;// 缓冲区占字节大小
char Buffer[gBufferSize];// 缓冲区
QSemaphore sFreeSize(gBufferSize);// 可用空间信号量,可用空间初始化为总大小
QSemaphore sOccupiedSize(0);// 已用空间信号量,初始化为0;
char MyChar[] = { 'A', 'B', 'C', 'D' };//char* MyChar = "ABCD";
int size = sizeof(MyChar) / sizeof(MyChar[0]);
生产者
class Producer :public QThread
{
public:
void run() override
{
for (int i = 0; i < gDataSize; ++i)
{
sFreeSize.acquire();
Buffer[i%gBufferSize] = MyChar[i%size];
sOccupiedSize.release();
}
}
};
消费者
class Consumer :public QThread
{
public:
void run() override
{
for (int i = 0; i < gDataSize; ++i)
{
sOccupiedSize.acquire();
std::cout << Buffer[i%gBufferSize];
sFreeSize.release();
if ((i + 1) % gBufferSize == 0)
{
std::cout << std::endl;
}
}
}
};
测试:
int main(int argc, char *argv[])
{
Producer p;
Consumer c;
p.start();
c.start();
p.wait();
c.wait();
getchar();
return 0;
}
结果:
所有代码:
#include <QObject>
#include <QtCore/QCoreApplication>
#include <QSemaphore>
#include <QThread>
#include <iostream>
const int gDataSize = 100000;// 总数据量
const int gBufferSize = 5000;// 缓冲区占字节大小
char Buffer[gBufferSize];// 缓冲区
QSemaphore sFreeSize(gBufferSize);// 可用空间信号量,可用空间初始化为总大小
QSemaphore sOccupiedSize(0);// 已用空间信号量,初始化为0;
char MyChar[] = { 'A', 'B', 'C', 'D' };//char* MyChar = "ABCD";
int size = sizeof(MyChar) / sizeof(MyChar[0]);
// 生产者
class Producer :public QThread
{
public:
void run() override
{
for (int i = 0; i < gDataSize; ++i)
{
sFreeSize.acquire();
Buffer[i%gBufferSize] = MyChar[i%size];
sOccupiedSize.release();
}
}
};
// 消费者
class Consumer :public QThread
{
public:
void run() override
{
for (int i = 0; i < gDataSize; ++i)
{
sOccupiedSize.acquire();
std::cout << Buffer[i%gBufferSize];
sFreeSize.release();
if ((i + 1) % gBufferSize == 0)
{
std::cout << std::endl;
}
}
}
};
int main(int argc, char *argv[])
{
Producer p;
Consumer c;
p.start();
c.start();
p.wait();
c.wait();
getchar();
return 0;
}