在使用標準庫中的佇列時遇到了一個問題。按自己的設想是使用佇列寫一個簡單的生產者消費者模型。代碼如下。但是執行一段時間之后在154行就會報錯。這個問題白色不得其解啊。
// queue.cpp : 定義控制臺應用程式的入口點。
//
#include "stdafx.h"
#include "queue.h"
#include <queue>
#include <iostream>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// 唯一的應用程式物件
CWinApp theApp;
using namespace std;
class CBusMsg
{
public:
CBusMsg()
{
m_pBuf=NULL;
m_nLen=0;
m_pNextMsg=NULL;
}
CBusMsg(WORD nAgentID, WORD nAgentExclue, BYTE* pBuf,int nLen)
{
m_nAgentID=nAgentID;
m_nAgentExclue=nAgentExclue;
m_nLen=nLen;
m_pBuf=new BYTE[m_nLen];
memcpy(m_pBuf,pBuf,nLen);
m_pNextMsg=NULL;
}
~CBusMsg()
{
if (m_pBuf!=NULL)
delete[] m_pBuf;
}
/****************************************************************
函 數 名:CBusMsg(CBusMsg &msg)
功能描述:拷貝建構式
參 數:
全域變數:
回傳值:
****************************************************************/
CBusMsg(const CBusMsg &msg)
{
m_nAgentID = 0;
m_nAgentExclue = 0;
m_nLen = 0;
m_pBuf = NULL;
m_pNextMsg = NULL;
}
/****************************************************************
函 數 名:operator!=
功能描述:多載函式
參 數:
全域變數:
回傳值:
****************************************************************/
bool operator!=(const CBusMsg& msg)
{
return true;
}
/****************************************************************
函 數 名:operator=
功能描述:多載賦值函式
參 數:
全域變數:
回傳值:
****************************************************************/
CBusMsg& operator=(const CBusMsg& msg)
{
if (*this != msg)
{
if (m_pBuf != NULL)
{
delete []m_pBuf;
m_pBuf = NULL;
m_nLen = 0;
}
m_nLen = msg.m_nLen;
m_pBuf = new BYTE[m_nLen];
memcpy(m_pBuf, msg.m_pBuf, m_nLen);
}
return *this;
}
WORD m_nAgentID; //0:群發,其它:單播
WORD m_nAgentExclue;
BYTE* m_pBuf;
int m_nLen;
CBusMsg *m_pNextMsg;
};
CRITICAL_SECTION m_csReceivedMsgQueue;
HANDLE m_hReceivedDataEvent;
HANDLE m_hEventStop;
queue<CBusMsg* > m_qReceivedMsgQueue;
UINT SendhreadProc( LPVOID pParam)
{
HANDLE hWaitObjList[2]={m_hEventStop,m_hReceivedDataEvent};
bool haveData = false;
DWORD dwWaitRes;
for(;;)
{
if(haveData)//如果還有未處理的資料不等待內核物件直接回傳
{
dwWaitRes=::WaitForMultipleObjects(2,hWaitObjList,FALSE,0);
}
else//如果沒有未處理的資料不等待內核物件直接回傳
{
dwWaitRes=::WaitForMultipleObjects(2,hWaitObjList,FALSE,200);
}
if((dwWaitRes-WAIT_OBJECT_0)==0)//,索引為0的內核物件被觸發,也就是停止執行緒被觸發
{
break;
}
haveData = false;
try
{
EnterCriticalSection(&m_csReceivedMsgQueue);
if(m_qReceivedMsgQueue.empty())
{
LeaveCriticalSection(&m_csReceivedMsgQueue);
continue;
}
CBusMsg*& busMsg = m_qReceivedMsgQueue.front();//取隊首元素
m_qReceivedMsgQueue.pop();//彈出隊首元素
if(NULL==busMsg)
{
LeaveCriticalSection(&m_csReceivedMsgQueue);
continue;
}
//ASSERT(busMsg->m_nLen<=0);
//pAgent->SetData(busMsg->m_pBuf,busMsg->m_nLen);
haveData = !m_qReceivedMsgQueue.empty();
LeaveCriticalSection(&m_csReceivedMsgQueue);
//程式運行一段時間后在這一行會出錯,錯誤原因時重復delete;
//但是程式中我每次取了隊首元素之后就行進了pop操作,再進行delete時我操作的物件已經不是佇列中的物件了啊。[/color]
//請各位老師指教,錯誤原因在哪?
delete busMsg;
//busMsg = NULL;
//ProcessData(pAgent);
}
catch(...)
{
LeaveCriticalSection(&m_csReceivedMsgQueue);
}
}
//delete pAgent;
return 0;
}
UINT PushData( LPVOID pParam)
{
BYTE pPacket[1000];
memset(pPacket,0,1000);
for (int i=0;i<100000;i++)
{
CBusMsg *pBusMsg;
pPacket[0]= i;
pBusMsg=new CBusMsg(i,0,pPacket,1000);
TRACE("請求向佇列加訊息\n");
EnterCriticalSection(&m_csReceivedMsgQueue);
TRACE("開始向佇列加訊息\n");
m_qReceivedMsgQueue.push(pBusMsg);
LeaveCriticalSection(&m_csReceivedMsgQueue);
SetEvent(m_hReceivedDataEvent);
}
return 0;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
InitializeCriticalSection(&m_csReceivedMsgQueue);
HMODULE hModule = ::GetModuleHandle(NULL);
if (hModule != NULL)
{
// 初始化 MFC 并在失敗時顯示錯誤
if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
{
// TODO: 更改錯誤代碼以符合您的需要
_tprintf(_T("錯誤: MFC 初始化失敗\n"));
nRetCode = 1;
}
else
{
m_hReceivedDataEvent =::CreateEvent(NULL,FALSE,FALSE,NULL);
m_hEventStop=::CreateEvent(NULL,FALSE,FALSE,NULL);
//創建發送執行緒
CWinThread* m_pSendThread=AfxBeginThread(SendhreadProc,NULL,THREAD_PRIORITY_NORMAL,0,CREATE_SUSPENDED,NULL);
m_pSendThread->m_bAutoDelete=FALSE;
m_pSendThread->ResumeThread();
CWinThread* processThread=AfxBeginThread(PushData,NULL,THREAD_PRIORITY_NORMAL,0,CREATE_SUSPENDED,NULL);
processThread->m_bAutoDelete=FALSE;
processThread->ResumeThread();
char str[1000];
cin.getline(str,900);
}
}
else
{
// TODO: 更改錯誤代碼以符合您的需要
_tprintf(_T("錯誤: GetModuleHandle 失敗\n"));
nRetCode = 1;
}
return nRetCode;
}
uj5u.com熱心網友回復:
不能用參考符,因為后呼叫了pop()CBusMsg*& busMsg = m_qReceivedMsgQueue.front();//取隊首元素
m_qReceivedMsgQueue.pop();//彈出隊首元素
uj5u.com熱心網友回復:
可以再說明白點碼?呼叫pop會執行什么操作?釋放記憶體?uj5u.com熱心網友回復:
您好,我不太明白同時使用&符和后面0pop操作為什么會造成錯誤。可以再講的清楚一些嗎?不勝感激
uj5u.com熱心網友回復:
參考的m_qReceivedMsgQueue.front()被pop()銷毀了,busMsg成了無效的參考。
uj5u.com熱心網友回復:
CBusMsg*& busMsg = m_qReceivedMsgQueue.front();//取隊首元素獲得的是個參考,那么使用這個busMsg資料時,不能pop他。要么 pAgent->SetData(busMsg 完畢了后再pop
要么
busMsg memcpy一個CBusMsg
uj5u.com熱心網友回復:
《Windows核心編程》uj5u.com熱心網友回復:
僅供參考://回圈向a函式每次發送200個位元組長度(這個是固定的)的buffer,
//a函式中需要將回圈傳進來的buffer,組成240位元組(也是固定的)的新buffer進行處理,
//在處理的時候每次從新buffer中取兩個位元組列印
#ifdef _MSC_VER
#pragma warning(disable:4996)
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _MSC_VER
#include <windows.h>
#include <process.h>
#include <io.h>
#define MYVOID void
#define vsnprintf _vsnprintf
#else
#include <unistd.h>
#include <sys/time.h>
#include <pthread.h>
#define CRITICAL_SECTION pthread_mutex_t
#define MYVOID void *
#endif
//Log{
#define MAXLOGSIZE 20000000
#define MAXLINSIZE 16000
#include <time.h>
#include <sys/timeb.h>
#include <stdarg.h>
char logfilename1[]="MyLog1.log";
char logfilename2[]="MyLog2.log";
static char logstr[MAXLINSIZE+1];
char datestr[16];
char timestr[16];
char mss[4];
CRITICAL_SECTION cs_log;
FILE *flog;
#ifdef _MSC_VER
void Lock(CRITICAL_SECTION *l) {
EnterCriticalSection(l);
}
void Unlock(CRITICAL_SECTION *l) {
LeaveCriticalSection(l);
}
void sleep_ms(int ms) {
Sleep(ms);
}
#else
void Lock(CRITICAL_SECTION *l) {
pthread_mutex_lock(l);
}
void Unlock(CRITICAL_SECTION *l) {
pthread_mutex_unlock(l);
}
void sleep_ms(int ms) {
usleep(ms*1000);
}
#endif
void LogV(const char *pszFmt,va_list argp) {
struct tm *now;
struct timeb tb;
if (NULL==pszFmt||0==pszFmt[0]) return;
vsnprintf(logstr,MAXLINSIZE,pszFmt,argp);
ftime(&tb);
now=localtime(&tb.time);
sprintf(datestr,"%04d-%02d-%02d",now->tm_year+1900,now->tm_mon+1,now->tm_mday);
sprintf(timestr,"%02d:%02d:%02d",now->tm_hour ,now->tm_min ,now->tm_sec );
sprintf(mss,"%03d",tb.millitm);
printf("%s %s.%s %s",datestr,timestr,mss,logstr);
flog=fopen(logfilename1,"a");
if (NULL!=flog) {
fprintf(flog,"%s %s.%s %s",datestr,timestr,mss,logstr);
if (ftell(flog)>MAXLOGSIZE) {
fclose(flog);
if (rename(logfilename1,logfilename2)) {
remove(logfilename2);
rename(logfilename1,logfilename2);
}
} else {
fclose(flog);
}
}
}
void Log(const char *pszFmt,...) {
va_list argp;
Lock(&cs_log);
va_start(argp,pszFmt);
LogV(pszFmt,argp);
va_end(argp);
Unlock(&cs_log);
}
//Log}
#define ASIZE 200
#define BSIZE 240
#define CSIZE 2
char Abuf[ASIZE];
char Cbuf[CSIZE];
CRITICAL_SECTION cs_HEX;
CRITICAL_SECTION cs_BBB;
struct FIFO_BUFFER {
int head;
int tail;
int size;
char data[BSIZE];
} BBB;
int No_Loop=0;
void HexDump(int cn,char *buf,int len) {
int i,j,k;
char binstr[80];
Lock(&cs_HEX);
for (i=0;i<len;i++) {
if (0==(i%16)) {
sprintf(binstr,"%03d %04x -",cn,i);
sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
} else if (15==(i%16)) {
sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
sprintf(binstr,"%s ",binstr);
for (j=i-15;j<=i;j++) {
sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
}
Log("%s\n",binstr);
} else {
sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
}
}
if (0!=(i%16)) {
k=16-(i%16);
for (j=0;j<k;j++) {
sprintf(binstr,"%s ",binstr);
}
sprintf(binstr,"%s ",binstr);
k=16-k;
for (j=i-k;j<i;j++) {
sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
}
Log("%s\n",binstr);
}
Unlock(&cs_HEX);
}
int GetFromRBuf(int cn,CRITICAL_SECTION *cs,struct FIFO_BUFFER *fbuf,char *buf,int len) {
int lent,len1,len2;
lent=0;
Lock(cs);
if (fbuf->size>=len) {
lent=len;
if (fbuf->head+lent>BSIZE) {
len1=BSIZE-fbuf->head;
memcpy(buf ,fbuf->data+fbuf->head,len1);
len2=lent-len1;
memcpy(buf+len1,fbuf->data ,len2);
fbuf->head=len2;
} else {
memcpy(buf ,fbuf->data+fbuf->head,lent);
fbuf->head+=lent;
}
fbuf->size-=lent;
}
Unlock(cs);
return lent;
}
MYVOID thdB(void *pcn) {
char *recv_buf;
int recv_nbytes;
int cn;
int wc;
int pb;
cn=(int)pcn;
Log("%03d thdB thread begin...\n",cn);
while (1) {
sleep_ms(10);
recv_buf=(char *)Cbuf;
recv_nbytes=CSIZE;
wc=0;
while (1) {
pb=GetFromRBuf(cn,&cs_BBB,&BBB,recv_buf,recv_nbytes);
if (pb) {
Log("%03d recv %d bytes\n",cn,pb);
HexDump(cn,recv_buf,pb);
sleep_ms(1);
} else {
sleep_ms(1000);
}
if (No_Loop) break;//
wc++;
if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
}
if (No_Loop) break;//
}
#ifndef _MSC_VER
pthread_exit(NULL);
#endif
}
int PutToRBuf(int cn,CRITICAL_SECTION *cs,struct FIFO_BUFFER *fbuf,char *buf,int len) {
int lent,len1,len2;
Lock(cs);
lent=len;
if (fbuf->size+lent>BSIZE) {
lent=BSIZE-fbuf->size;
}
if (fbuf->tail+lent>BSIZE) {
len1=BSIZE-fbuf->tail;
memcpy(fbuf->data+fbuf->tail,buf ,len1);
len2=lent-len1;
memcpy(fbuf->data ,buf+len1,len2);
fbuf->tail=len2;
} else {
memcpy(fbuf->data+fbuf->tail,buf ,lent);
fbuf->tail+=lent;
}
fbuf->size+=lent;
Unlock(cs);
return lent;
}
MYVOID thdA(void *pcn) {
char *send_buf;
int send_nbytes;
int cn;
int wc;
int a;
int pa;
cn=(int)pcn;
Log("%03d thdA thread begin...\n",cn);
a=0;
while (1) {
sleep_ms(100);
memset(Abuf,a,ASIZE);
a=(a+1)%256;
if (16==a) {No_Loop=1;break;}//去掉這句可以讓程式一直回圈直到按Ctrl+C或Ctrl+Break或當前目錄下存在檔案No_Loop
send_buf=(char *)Abuf;
send_nbytes=ASIZE;
Log("%03d sending %d bytes\n",cn,send_nbytes);
HexDump(cn,send_buf,send_nbytes);
wc=0;
while (1) {
pa=PutToRBuf(cn,&cs_BBB,&BBB,send_buf,send_nbytes);
Log("%03d sent %d bytes\n",cn,pa);
HexDump(cn,send_buf,pa);
send_buf+=pa;
send_nbytes-=pa;
if (send_nbytes<=0) break;//
sleep_ms(1000);
if (No_Loop) break;//
wc++;
if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
}
if (No_Loop) break;//
}
#ifndef _MSC_VER
pthread_exit(NULL);
#endif
}
int main() {
#ifdef _MSC_VER
InitializeCriticalSection(&cs_log);
InitializeCriticalSection(&cs_HEX);
InitializeCriticalSection(&cs_BBB);
#else
pthread_t threads[2];
int threadsN;
int rc;
pthread_mutex_init(&cs_log,NULL);
pthread_mutex_init(&cs_HEX,NULL);
pthread_mutex_init(&cs_BBB,NULL);
#endif
Log("Start===========================================================\n");
BBB.head=0;
BBB.tail=0;
BBB.size=0;
#ifdef _MSC_VER
_beginthread((void(__cdecl *)(void *))thdA,0,(void *)1);
_beginthread((void(__cdecl *)(void *))thdB,0,(void *)2);
#else
threadsN=0;
rc=pthread_create(&(threads[threadsN++]),NULL,thdA,(void *)1);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1);
rc=pthread_create(&(threads[threadsN++]),NULL,thdB,(void *)2);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1);
#endif
if (!access("No_Loop",0)) {
remove("No_Loop");
if (!access("No_Loop",0)) {
No_Loop=1;
}
}
while (1) {
sleep_ms(1000);
if (No_Loop) break;//
if (!access("No_Loop",0)) {
No_Loop=1;
}
}
sleep_ms(3000);
Log("End=============================================================\n");
#ifdef _MSC_VER
DeleteCriticalSection(&cs_BBB);
DeleteCriticalSection(&cs_HEX);
DeleteCriticalSection(&cs_log);
#else
pthread_mutex_destroy(&cs_BBB);
pthread_mutex_destroy(&cs_HEX);
pthread_mutex_destroy(&cs_log);
#endif
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/84174.html
標籤:界面
上一篇:疵點檢測能否提供個思路?小白
