我的程序有一个共享内存,任何访问通过信号量semid进行同步。 它在进程中工作正常。 现在,我把一个线程放在一个进程中。 在主线程( thread0
)中,它有一个while(wait())
循环来持续访问共享内存( wait()
是一个使用semid
获取内存拷贝的semid
)并且在信号量semid
上semid
P
和V
操作。 现在我得到了一个"P operation on Semaphore failed."
当线程1试图做一个P
操作。
主线:
... while(1) { if ((RetVal = WAIT_MSG( p1, &Msg )) !=SUCC) { switch ( RetVal ) { ... } } }
thread1: ... send(src, dst, &msg, lenght); /* both send and wait have an operation P and V on semid by calling the following */ DMINT tdm_sem_p( key_t semid ) { struct sembuf sem_b; sem_b.sem_num = 0; sem_b.sem_op = -1; sem_b.sem_flg = SEM_UNDO; if (semop(semid, &sem_b, 1) == -1) { printf("thread %u: errno = %d\n", (unsigned int)pthread_self(),errno); return S_PFAIL; } return SUCC; } DMINT tdm_sem_v( key_t semid ) { struct sembuf sem_b; sem_b.sem_num = 0; sem_b.sem_op = 1; sem_b.sem_flg = SEM_UNDO; if (semop(semid, &sem_b, 1) == -1) { return S_VFAIL; } return SUCC; } /* semid is init by the following */ DMINT tdm_set_sem(key_t semid) { union semun sem_union; sem_union.val = 1; if (semctl(semid, 0, SETVAL, sem_union) == -1) { return FAILURE; } return SUCC; } --------------------------------------
从GBD,我得到了:
(gdb) s [Switching to Thread -1208808560 (LWP 3904)] SEND_MSG (SrcModule=51, DstModule=99, msg_ptr=0xb7f2ff94, MsgLength=28) at tdm_ipc.c:287 287 TDM_SEM_P( semid ); (gdb) s [Switching to Thread -1208596800 (LWP 3899)] tdm_sem_v (mid=RM) at tdm_ipc.c:595 595 sem_b.sem_num = 0; (gdb) s 596 sem_b.sem_op = 1; (gdb) s 597 sem_b.sem_flg = SEM_UNDO; (gdb) s 599 if (semop(semid, &sem_b, 1) == -1) (gdb) s 604 return SUCC; (gdb) s 605 } (gdb) s RM:3899: V operation on Semaphore . [Switching to Thread -1208808560 (LWP 3904)] tdm_sem_p (mid=99) at tdm_ipc.c:578 578 sem_b.sem_num = 0; (gdb) s 579 sem_b.sem_op = -1; (gdb) s 580 sem_b.sem_flg = SEM_UNDO; (gdb) s 582 if (semop(semid, &sem_b, 1) == -1) (gdb) s 584 return S_PFAIL; (gdb) s 588 } (gdb) s :0: P operation on Semaphore failed. thread 3086489280: **errno = 4** [Switching to Thread -1208596800 (LWP 3899)]
semop
函数在一个进程中不能在线程中工作? 如果比赛发生,我期待一个挂断等待而不是失败。
errno 4的剂量有什么意义? 我正在看它的意思。
谢谢。