gpt4 book ai didi

将结构数组复制到共享内存中

转载 作者:太空宇宙 更新时间:2023-11-04 03:32:11 24 4
gpt4 key购买 nike

我有多个进程对同一数据进行操作。我想将数据保存在共享内存中。问题是我似乎无法保存(或检索)。

我的完整代码在这里: https://github.com/kasperekt/LLGame/blob/master/server_src/game_state.c#L74

但问题似乎出在这些函数中:

typedef struct game_state {
int resources;
int wins;
army_t *army;
} game_state_t;

...

static game_state_t *players[2] = { NULL, NULL };
static game_state_t **mem_state = NULL;

...

void attach_state() {
mem_state = get_memory_data(0);
players[0] = mem_state[0];
players[1] = mem_state[1];
}

void save_state() {
if (mem_state == NULL) {
mem_state = get_memory_data(0);
}

mem_state[0] = players[0];
mem_state[1] = players[1];
detach_memory_data(mem_state);
}

以及处理此数据的示例函数:

void increment_resources(int player_id) {
attach_state();
const int workers_count = players[player_id]->army->workers;
players[player_id]->resources += RESOURCES_STEP + (workers_count * 5);
save_state();
}

我应该如何将它保存到内存中?它是如何工作的?我找不到这个问题的答案。

也许这段代码也有帮助:

game_state_t **get_memory_data(char *shmaddr) {
const int shmat_flag = 0;
return shmat(memory_id, shmaddr, shmat_flag);
}

void detach_memory_data(game_state_t **data) {
if (shmdt(data) == -1) {
perror("Error detaching memory: ");
exit(1);
};
}

最佳答案

你有 game_state_t 变量。如果要存储多个状态,则只需要一维数组。这是示例。

game_state_t *memstate;
...
memstate = (game_state_t *) malloc( n * sizeof(game_state_t)); /* alloc memory for n states */

shmptr = shmat(...);

memcpy(shmptr, memstate, size); /* size for example n * size of(game_state_t)); */

或者只使用共享内存。

memstate = shmat(...);

如评论中所述,结构的指针成员需要指向共享内存。

例子;

memstate.x = memstate + offset; /* use different offsets based on your usage */ 

关于将结构数组复制到共享内存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35507687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com