我试图实现一个简单的二进制信号量,以保护关键变量不受错误值的影响,如下所示:
sem_init(&phore, 0, 1);//sem_t phore;
这是锁定和重新定位:
void doc(){
sem_wait(&phore);
stats->npaten++;
sem_post(&phore);
printf("Doctor %d ready for duty\n%d\n",getpid(),stats->npaten);
}
doc
是10个进程的worker函数,npaten
是共享内存中结构的变量。
npaten的预期值应为10,但每次打印出1。提前致谢
编辑:有问题的结构:
struct stats{
int nptri;
int npaten;
float inicio;
float fim;
float avgtime;
}*stats;
和共享内存初始化:
void sharedmemory(){
shmid = shmget(IPC_PRIVATE, sizeof(struct stats),IPC_CREAT|0766);
stats = (struct stats *)shmat(shmid, NULL, 0);
if(shmid == -1){
perror("Couldn't create shared memory segment\n");
exit(1);
}
if(stats == (struct stats *)-1){
perror("Couldn't attach shared memory segment to the adress space\n");
exit(1);
}
printf("Shared memory created successfully\n");
}