【发布时间】:2011-10-25 12:38:10
【问题描述】:
假设消息以 1 秒的间隔来自外部源生成器。我有两个处理函数,每当这些消息基于消息的字段出现时,它们就会被调用
我有一个函数可以创建一个名为 WriteSM 的线程例程。
考虑一个包含 2 个字段的 2 个字节的消息 1)数据 2类型
每个字段都有两个处理函数,如下所示
void HandlerforData(char data)
void handlerforType(char Type)
/*This is the sample piece of code*/
char buffer[4];/*Global buffer*/
int index = 0;
static int flag = 0;/*A global static flag*/
void HandlerforData(char data);
void WriteSM(void);
void handlerforType(char Type);
/*Two handler functions*/
void HandlerforData(char data)
{
buffer[index] = data;
}
void handlerforType(char Type)
{
buffer[index+1] = type;
buffer[index+3] = '\0';/*Null terminated the string*/
index = 0;
flag = 1
}
void WriteSM(void)
{
while(1)
{
if(flag ==1)
{
/*Opens a shared memory and writes to the shared memory*/
flag =0/*Reset the flag*/
}
}
}
假设我的消息间隔为 1 秒,我将如何确保缓冲区不会被下一帧消息覆盖?
如果您有任何问题,请务必回复我
感谢和问候 麦迪
【问题讨论】:
-
我认为您需要告诉我们(假定的)多线程是如何实现的——特别是如果可以使用相同的“全局”缓冲区从不同线程调用这段代码,则会出现问题。
-
用更多信息修改了代码
-
您是否正在尝试将数据写入缓冲区(至少应将其声明为 char buffer[2])?这个数据是二进制的吗? '0' 或 null 是有效值吗?
-
@ChrisBD..抱歉造成混淆。它是一个字符缓冲区[4]。