C++ 无法使用Boost线程中的消息队列接收消息
我需要创建一个基于事件的多线程应用程序,我正在尝试使用boost::thread和boost/interprocess/ipc/message_queue在线程之间发送消息。 我目前正在做的是让线程在其workerfunction中等待消息。 实际上,这只是一个基本的开始,发送方和接收方都是同一个线程,在后面的阶段,我想存储一个对应于每个线程的消息队列列表,然后相应地获取它或类似的东西。 但是现在,根据下面的代码,我正在使用C++ 无法使用Boost线程中的消息队列接收消息,c++,multithreading,boost,boost-thread,boost-interprocess,C++,Multithreading,Boost,Boost Thread,Boost Interprocess,我需要创建一个基于事件的多线程应用程序,我正在尝试使用boost::thread和boost/interprocess/ipc/message_queue在线程之间发送消息。 我目前正在做的是让线程在其workerfunction中等待消息。 实际上,这只是一个基本的开始,发送方和接收方都是同一个线程,在后面的阶段,我想存储一个对应于每个线程的消息队列列表,然后相应地获取它或类似的东西。 但是现在,根据下面的代码,我正在使用 //in a common class typedef struct
//in a common class
typedef struct s_Request{
int id;
}st_Request;
//in thread(XYZ) class
st_Request dataone;
message_queue *mq;
void XYZ::threadfunc(void *ptr)
{
XYZ*obj = (XYZ*) ptr;
obj->RecieveMsg();
}
void XYZ::RecieveMsg()
{
message_queue mq1(open_only,"message_queue");
if(!(mq1.try_receive(&dataone, sizeof(st_Request), recvd_size, priority)))
printf("msg not received");
printf("id = %d",dataone.id);
}
void XYZ::Create()
{
mq= new message_queue(open_or_create,"message_queue",100,sizeof(st_Request));
boost:thread workerthread(threadfunc,this);
workerthread.join();
}
void XYZ::Send(st_Request *data)
{
if (!(mq->try_send(data, sizeof(st_Request), 0)))
printf("message sending failed");
}
//I am calling it like
class ABC: public XYZ
{
..some functions to do stuff... };
void ABC::createMSGQ()
{
create();
st_Request *data;
data->id =10;
send(data);
}
我的线程正在ReceiveMsg中等待,但我没有收到任何消息,直到Send函数输入并在代码崩溃之前打印出来。
请指导我做错了什么,如果方法完全错误,我愿意采用新方法
另外,这是我关于堆栈溢出的第一个问题,我尝试了遵循指导原则,但如果我偏离了任何地方,请纠正
st_Request *data;
data->id =10;
数据
未初始化,无法取消引用。在解除引用之前,指针应该指向某个对象
我不明白这个函数的意义:
void XYZ::Create()
{
mq= new message_queue(open_or_create,"message_queue",100,sizeof(st_Request));
boost:thread workerthread(threadfunc,this);
workerthread.join();
}
创建一个新线程,然后阻塞并等待它完成,以便可以加入它。为什么不在这里完成工作,而不是创建一个新线程并等待它完成
什么是threadfunc
?你是说ThreadFunc
这个函数写得很奇怪:
void XYZ::ThreadFunc(void *ptr)
{
XYZ*obj = (XYZ*) ptr;
obj->RecieveMsg();
}
为什么不将参数传递为XYZ*
,而不是void*
?Boost.Thread并不要求所有内容都作为void*
传递。该函数是静态的吗?它不需要是:
struct XYZ {
void threadFunc();
void create();
void recv();
};
void XYZ::threadFunc()
{
recv();
}
void XYZ::create()
{
boost::thread thr(&XYZ::threadFunc, this);
thr.join();
}
您应该正确缩进代码,使其可读。您可以粘贴代码,然后高亮显示它,并使用Ctrl-K(或{}图标)一致地缩进整个块。总之,什么是
threadfunc
?为什么将参数传递给XYZ::ThreadFunc
作为void*
而不是XYZ*
?@JonathanWakely-ThreadFunc是创建的workerthread在创建时开始执行的函数。从这里开始-boost:threadworkerThread(threadfunc,this)。老实说,void*是根据一个示例传递的,后来我将其转换为XYZ*以访问其他成员函数,因为ThreadFunc是一个静态成员函数。我没有问什么是ThreadFunc
,我问的是ThreadFunc
是什么,您在Create
中使用了它。在C++中,代码> TraceFunc与