0

我希望有人可以帮助我解决我需要修复的 C 程序中的一些不可预测的行为:

我有两个 Xenomai 实时任务(线程)等待它们从两条 CAN 总线之一接收到传入消息。
每个任务都调用一个函数 checkMessageNumber() 但是我得到了不可预测的结果。

请注意,我使用的是基于优先级的单线程系统。一个线程比另一个线程具有优先级,但是当另一个线程具有优先权时,一个线程可能会在执行过程中部分执行。
未来有可能将硬件升级为多线程系统,但是这部分程序仍将仅限于单个线程(一个 CPU 内核)。

我的理解是每个线程都会调用它自己的这个函数的实例,所以我不知道发生了什么。

int getMessageIndex(unsigned int msg_number)
{
    unsigned int i = 0;
    while(i < global_number_message_boxes)
    { 
        if (global_message_box[i].id == msg_number}
            return i; // matched the msg number, so return the index number
        i++;
    }
    return -1; // no match found
}

最初这个函数是高度不可预测的,并且由于消息流入并由两个任务处理(取决于消息来自哪个硬件总线),即使传入的“msg_number”确实与“id”匹配,该函数有时也会返回 -1 ' 在 'global_message_box' 结构中。

通过将'global_number_message_boxes'设置为整数,我能够使其更好地工作:
例如。 while(i < 50)
但是,即使应该有匹配项,该函数有时仍会返回 -1。

我只在读取全局变量,那么为什么它们会损坏?我需要了解什么?

我的想法是简化事情,因此传入的“msg_number”只是“global_message_box”中的“id”。
然后每个线程将直接写入结构,而不必检查要写入的“id”。
使用互斥锁有多重要?由于系统设计,每个线程永远不会写入结构的同一部分,所以我不确定它是否重要?

谢谢。

4

2 回答 2

3

This likely comes down to lack of thread synchronisation around the global struct: you say this function is just reading. Sure, but what if another thread calls another function that writes global_number_message_boxes or global_message_box? In a system where you have globals and multiple threads accessing them the safes rule is: put a lock around every access. Maybe the platform you use even supports read/write locks, so multiple threads can read at the same time as long as none is writing.

于 2012-10-18T08:22:14.573 回答
1

Lock 和 Semaphores 将成为您的朋友。使用两个线程写入数据会导致许多问题。

当线程进入函数时,您将不得不阻塞其他线程并在退出时取消阻塞这些线程。这将确保线程安全操作并产生一致的结果。

于 2012-10-18T08:24:10.753 回答