我最近在C ++中开发了一个用于学习互斥的测试项目。
我创建了两个包装函数:
void Semaphore::semaphore_await(int sem_cluster_id, unsigned short which) //semaphore_p
{
int zmien_sem;
sembuf bufor_sem;
bufor_sem.sem_num = which;
bufor_sem.sem_op = -1;
bufor_sem.sem_flg = SEM_UNDO;
zmien_sem = semop(sem_cluster_id, &bufor_sem, 1);
if (zmien_sem == -1) {
printf("Nie moglem zamknac semafora.\n");
exit(EXIT_FAILURE);
} else {
// printf("Semafor S%d zostal zamkniety.\n", which);
}
}
void Semaphore::semaphore_unlock(int semid, unsigned short which) //semaphore_v
{
int zmien_sem;
sembuf bufor_sem;
bufor_sem.sem_num = which;
bufor_sem.sem_op = 1;
bufor_sem.sem_flg = SEM_UNDO;
zmien_sem = semop(semid, &bufor_sem, 1);
if (zmien_sem == -1) {
printf("Nie moglem otworzyc semafora.\n");
exit(EXIT_FAILURE);
} else {
// printf("Semafor S%d zostal otwarty.\n", which);
}
}
我产生了一些进程来竞争资源,并且有以下机构:
void critical_section(int semid, unsigned short semaphor_number){
Semaphore::semaphore_await(semid, semaphor_number);
std::cout<<"I am process:"<<getpid()<<" and I am in critical section!"<<std::endl;
// sleep(1);
Semaphore::semaphore_unlock(semid, semaphor_number);
}
问题在于我无法重现互斥现象。一旦单个prcoess进入该部分,它就不会让另一个进程进入该部分,但大多数时候同一个进程执行临界部分...
I am process:32339 and I am in critical section!
I am process:32346 and I am in critical section!
I am process:32346 and I am in critical section!
I am process:32346 and I am in critical section!
I am process:32346 and I am in critical section!
I am process:32346 and I am in critical section!
I am process:32346 and I am in critical section!
I am process:32346 and I am in critical section!
I am process:32346 and I am in critical section!
I am process:32346 and I am in critical section!
I am process:32346 and I am in critical section!
I am process:32341 and I am in critical section!
I am process:32341 and I am in critical section!
在Manjaro或Ubuntu这样的Linux平台下更加令人担忧的是它完美无缺。