gpt4 book ai didi

c - 使用共享内存时遇到一些问题

转载 作者:行者123 更新时间:2023-11-30 15:48:36 25 4
gpt4 key购买 nike

我正在尝试使用共享内存中的指针来编译代码。我想使用互斥变量来检查是否可以进行进程间同步。但 Xcode 给我错误“解析问题“预期表达式”并突出显示该行
*(pthread_mutex_t*)shm_addr = PTHREAD_MUTEX_INITIALIZER; 为红色。
这是代码。

#include <sys/ipc.h>
#include <sys/shm.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

#define KEY_NUM 9527
#define MEM_SIZE 4096

pthread_mutex_t test;
int main(int argc, char * argv[])
{
int shm_id;
void *shm_addr;

if( (shm_id = shmget((key_t)KEY_NUM, MEM_SIZE, IPC_CREAT | 0666)) == -1)
{
printf("fail to allocate a shared memory.\n");
return -1;
}

if((shm_addr = shmat(shm_id, (void*)0,0)) == (void*)-1)
{
printf("fail to attach shared memory.\n");
return -1;
}

*(pthread_mutex_t*)shm_addr = PTHREAD_MUTEX_INITIALIZER; // error.


test = PTHREAD_MUTEX_INITIALIZER;
// this statement works well.
*(int*)(shm_addr+64) = 10000; // this statement also works well.

// information useful to you.
// sizeof(pthread_mutex_t*) : 64
// OS X Mountain Lion 64bits
return 0;
}

我不知道为什么。有人可以帮忙吗?

谢谢。

最佳答案

要在共享内存中使用互斥体,您首先需要一个支持此功能的系统(您没有告诉我们),然后您必须相应地初始化互斥体。宏 PTHREAD_MUTEX_INITIALIZER 不适合这种情况,您必须通过正确的参数集动态使用 pthread_mutex_init

与此相关的文本始终是 POSIX 标准,您可以通过搜索 name_of_the_function_you_are_interested_in 和“opengroup”轻松找到该标准。对于pthread_mutex_init,它指出:

In cases where default mutex attributes are appropriate, the macro PTHREAD_MUTEX_INITIALIZER can be used to initialize mutexes that are statically allocated. The effect shall be equivalent to dynamic initialization by a call to pthread_mutex_init() with parameter attr specified as NULL, except that no error checks are performed.

而函数 pthread_mutexattr_setpshared 的相关部分指出:

The process-shared attribute is set to PTHREAD_PROCESS_SHARED to permit a mutex to be operated upon by any thread that has access to the memory where the mutex is allocated, even if the mutex is allocated in memory that is shared by multiple processes. If the process-shared attribute is PTHREAD_PROCESS_PRIVATE, the mutex shall only be operated upon by threads created within the same process as the thread that initialized the mutex; if threads of differing processes attempt to operate on such a mutex, the behavior is undefined. The default value of the attribute shall be PTHREAD_PROCESS_PRIVATE.

此外,在现代系统和新代码中,不要使用古老的 shmat 调用。现代的替代方案是 shm_openmmap 的组合。

关于c - 使用共享内存时遇到一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16749924/

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