赞
踩
- /**********res.h声明全局变量************/
- #pragma once
-
- #include <QSemaphore>
-
- const int g_nDataSize = 1000; // 生产者生产的总数据量
- const int g_nBufferSize = 500; // 环形缓冲区的大小
-
- extern char g_szBuffer[]; // 环形缓冲区
- extern QSemaphore g_qsemFreeBytes; // 控制环形缓冲区的空闲区(指生产者还没填充数据的区域,或者消费者已经读取过的区域)
- extern QSemaphore g_qsemUsedBytes; // 控制环形缓冲区中的使用区(指生产者已填充数据,但消费者没有读取的区域)
- /**************************/
- /**********res.cpp定义全局变量************/
- #pragma once
- #include "res.h"
-
- // 定义全局变量
- char g_szBuffer[g_nBufferSize];
- QSemaphore g_qsemFreeBytes(g_nBufferSize);
- QSemaphore g_qsemUsedBytes;
- /**************************/
- /**********类ConsumerThread使用全局变量************/
- #include "consumerthread.h"
- #include "res.h"
- #include <QDebug>
-
- ConsumerThread::ConsumerThread(QObject* parent)
- : QThread(parent) {
-
- }
-
- ConsumerThread::ConsumerThread() {
-
- }
-
- ConsumerThread::~ConsumerThread() {
-
- }
-
- void ConsumerThread::run() {
- for (int i = 0; i < g_nDataSize; i++) {
- g_qsemUsedBytes.acquire();
- qDebug()<<"Consumer "<<g_szBuffer[i % g_nBufferSize];
- g_szBuffer[i % g_nBufferSize] = ' ';
- g_qsemFreeBytes.release();
-
- }
- qDebug()<<"&&Consumer Over";
- }
- /**************************/

- /***********res.h**********/
- static char g_szBuffer[6] = "12345";
- void fun();
- /************************/
- /***********res.cpp**********/
- #include "res.h"
- #include <iostream>
- using namespace std;
-
- void fun() {
- for (int i = 0; i < 6; i++) {
- g_szBuffer[i] = 'A' + i;
- }
- cout<<g_szBuffer<<endl;
- }
- /************************/
- /***********test1.h**********/
- void fun1();
- /************************/
- /***********test1.cpp**********/
- #include "test1.h"
- #include "res.h"
- #include <iostream>
- using namespace std;
-
- void fun1() {
- fun();
-
- for (int i = 0; i < 6; i++) {
- g_szBuffer[i] = 'a' + i;
- }
- cout<<g_szBuffer<<endl;
- }
- /************************/
- /***********test2.h**********/
- void fun2();
- /************************/
- /***********test2.cpp**********/
- #include "test2.h"
- #include "res.h"
- #include <iostream>
- using namespace std;
-
- void fun2() {
- cout<<g_szBuffer<<endl;
- }
- /************************/
- /***********main.cpp**********/
- #include "test1.h"
- #include "test2.h"
-
- int main() {
- fun1();
- fun2();
-
- system("PAUSE");
- return 0;
- }
- /************************/
- extern const char g_szBuffer[]; //写入 .h中
- const char g_szBuffer[] = "123456"; // 写入.cpp中
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。