创建静态全局的多个实例/副本

标签 c multithreading ipc extern

不确定我的标题措辞是否正确,但请耐心等待,所有内容都会得到解释...

我们有一组代码不是在这里发明的,它使用进程间通信(IPC 消息传递)。该方案的大致轮廓是这样的:

comms.c 包含:

static int our_id;

void init_messaging(int id)
{
   our_id = id;
   Msg_Init(KEY);
}

void get_some_data_from_elsewhere(target_id)
{
   send_message(target_id, our_id); // Send to target, return to us
   rcv_message(<our_id>); // get messages addressed to <our_id>
}

然后 stuff.c 可能会做:

init_messaging(ID_STUFF);
get_some_data(target);

foo.c 也可能做:

init_messaging(ID_FOO);
get_some_data(target);

这是如何工作的/应该工作/Elbonian Code Slaves 似乎期望它工作:

当 stuff.c 调用 init_messaging 时,our_id 设置为 ID_STUFF,并且来自该进程的任何进一步调用都将有变量“ID_STUFF”可用,以确保消息队列上的回复返回到正确的进程。

但是,如果我们遇到这种情况,即从同一个地方产生两个或更多线程,它们都会失败:

stuff.c 可能会做:

void stuff_thread()
{
    init_messaging(ID_STUFF);
    get_some_data(target);
}

void things_thread()
{
    init_messaging(ID_THINGS);
    get_some_data(target);
}

如果发生这种情况,当 stuff_thread 启动时,our_id 设置为 ID_STUFF,但随后当 things_thread 启动时,our_id 被覆盖为 ID_THINGS,因此 things_thread 最终可以获取用于 stuff_thread 的数据。

现在,这显然是一个相当不稳定的问题,但我不确定这样做的正确/最糟糕的方法是什么,而不必将额外的变量传递给对 get_some_data() 等的每次调用。

看来我们需要的是此处“seldom_correct.h”示例中提到的内容: https://stackoverflow.com/a/1433387/1389218 每次包含 comms.h 都会产生一个新的 our_id 副本 - 除了我们每次调用 init_messaging() 时都需要多个副本;

或者让 our_id 成为一个 extern,像这样: comms.h

extern int our_id;

stuff.c 可能会做:

#include "comms.h"

void stuff_thread()
{
    our_id = ID_STUFF;
    init_messaging(our_id);
    get_some_data(target);
}

搜索一轮 SO 尚未产生任何优雅的答案。

最佳答案

向 ChrisJ.Kiick 致敬,声明:

static __thread int our_id;

成功了!

关于创建静态全局的多个实例/副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21483974/

相关文章:

c - C语言中的sizeof枚举

C中#include的成本

.net - .NET ThreadPool 线程在返回池时是否会重置?

Python [子]进程向 Node [父]进程发送消息

c - 如何模拟头文件中的函数?

c - 以下每个项目都有一个错误(我需要修复它们)

php - 从 PHP worker 到 Python 线程

c# - C#多线程访问单一方法

java - Android: Intent 和组件之间交换数据

angularjs - Angular Controller 中的 Electron IPC