请问这个消息链表应该怎么创建、操作好呢?
我有一个消息链表pList,目前节点结构我定义如下:
typedef struct DataBuf
{
char buffer[10240];
int length;
DataBuf *pNext;
}DataBuf;
有两个线程同时对这个消息链表进行操作,线程1对该链表进行写操作,线程2对该链表进行读操作,读完成后线程2对该节点进行删除。
现在的问题是线程1对时时性要求比较高,线程2对链表操作时间比较长,加了互斥量后一段时间后线程1就会停止运行。
有没有办法不加互斥量能够在两个线程中添加、删除链表节点而不会出现问题。或者有其它方法更好了,多谢大家帮忙。
[解决办法]
互斥部分应该没问题,你可以试试用STL,看是否能满足你的需求
[解决办法]
用临界区不行吗?
临界区比互斥节省时间。
[解决办法]
用stl的list的一种可能实现
#include "stdafx.h "
#include "windows.h "
#include "iostream "
#include "list "
using namespace std;
typedef struct DataBuf
{
char buffer[10240];
int length;
}DataBuf;
list <DataBuf*> m_List;
HANDLE hEvent = CreateEvent(NULL,FALSE,FALSE,NULL);
CRITICAL_SECTION rSection;
BOOL bExit=FALSE;
DWORD WINAPI WriteProcess(LPVOID lp)
{
for (int i=0;i <1000;i++)
{
DataBuf *pStruct =new DataBuf;
pStruct-> length =i;
memcpy(pStruct-> buffer, "just test ",9);
EnterCriticalSection(&rSection);
m_List.push_back(pStruct);
LeaveCriticalSection(&rSection);
SetEvent(hEvent);
Sleep(5);
}
EnterCriticalSection(&rSection);
LeaveCriticalSection(&rSection);
bExit=TRUE;
SetEvent(hEvent);
return 0;
}
DWORD WINAPI ReadProcess(LPVOID lp)
{
while (1)
{
if (bExit)
{
return 0;
}
WaitForSingleObject(hEvent,INFINITE);
EnterCriticalSection(&rSection);
if (m_List.empty())
{
LeaveCriticalSection(&rSection);
continue;
}
DataBuf * p=m_List.front();
m_List.pop_front();
LeaveCriticalSection(&rSection);
//add your code here to deal with the p point
delete p;
}
return 0;
}
int main(int argc, char* argv[])
{
InitializeCriticalSection(&rSection);
printf( "Hello World!\n ");
HANDLE handle[2];
handle[0] =CreateThread(NULL,NULL,ReadProcess,NULL,NULL,NULL);
handle[1] =CreateThread(NULL,NULL,WriteProcess,NULL,NULL,NULL);
WaitForMultipleObjects(2,handle,TRUE,INFINITE);
return 0;
}
[解决办法]
用临界区好,临界区比互斥省时,而且容易控制
[解决办法]
有同步就行。进程内建议用临界区。
[解决办法]
个人认为还是用临界区比较好,将对这个消息链表的操作搞成一个原子操作。
不过如果觉得效率对你必是很重要的话,我觉得用事件内核对象好一点。(我也是一个小白,不对的地方请谅解 阿)
[解决办法]
临界区较快
可是,为什么操作较长?,不是从线程 2 着手吧!
不应该很长,应该极短才对,是你的程序结构和数据结构问题
[解决办法]
互斥量没有控制好!否则不会死锁的!