簡體   English   中英

信號量問題,不等待

[英]Semaphore Problems, not Waiting

我有一個信號量問題,盡管您可以幫助我。.好的,首先讓我展示一下我在做什么。 我必須使用c程序,一台服務器和其他命名的客戶端。

在服務器上,我這樣做:

#ifdef _SEM_SEMUN_UNDEFINED    //here I define semun, in case that is not defined
#undef _SEM_SEMUN_UNDEFINED
union semun {
int val;
struct semid_ds *buf;
unsigned short int *array;
struct seminfo *__buf;
};
#endif

union semun semopts;
int semID;

semID = semget(1000, 1, 0600 | IPC_CREAT | IPC_EXCL); //I want this gives error, if there is already a sem on that key
if(semID < 0){
   perror(semID);
   exit(1);
}
semopts.val = 10;
semctl(semID, 0, SETVAL, semopts);  //Here I set the val for the first sem of the group, I want it with value 10

好的,這是我的服務器文件,現在在客戶端上,我需要做的是:

可以同時從內存中讀取10個客戶端,因此對於每個讀取器,我在sem上執行-1。 1個客戶端可以同時在內存上寫入,而沒有人可以讀取,因此在這種情況下,我對sem做-10,對嗎?

所以這是我的客戶程序:

struct sembuf UP10 = {0, 10, 0};
struct sembuf DOWN10 = {0, -10, 0};
struct sembuf UP1 = {0, 1, 0};
struct sembuf DOWN1 = {0, -1, 0};
int semID;
semID = semget(1000, 1, 0600 | IPC_CREAT);
if(semID < 0){
  perror(semID);
  exit(1);
}

//Okay now its here on my switch where they read or write

switch(selection[0]){ //This store the number from a scanf
case '1':

semop(semID, &DOWN1, 1);
functionToRead(..);
semop(semID, &UP1, 1);
break;

case '2': //Here the client also read from memory

semop(semID, &DOWN1, 1);
functionToReadAlsoMemory(...);
semop(semID, &UP1, 1);
break;

case '3': //Here is the block where the client WRITES on memory so use the struct DOWN10 and UP10

semop(semID, &DOWN10, 1);
functionToWriteOnMemory(...);
semop(semID, &UP10, 1);
break;

}

好的,問題是:

當我按3(寫到內存的塊)時,程序對sem執行-10,然后在該函數上輸入,其中有scanf,因此sem會一直為0,直到它退出該函數為止。 scanf。 在這種情況下,如果在客戶機上進行寫操作,而我嘗試打開另一個客戶機並進行寫操作,它將一直等待,直到另一個客戶機離開該功能並執行sem UP10。 好吧,這就是我想要的,然后等待的客戶端通過該函數進行編寫。

但是,如果有一個客戶端正在使用該功能(該客戶端執行了DOWN10,所以sem為0),而我嘗試從內存中讀取(對於大小寫“ 1”或大小寫“ 2”),那么他實際上可以! 但是不應該! 因為如果sem仍為0,則他無法使sem DOWN1,對嗎?

我想你們在這里理解我的問題,我有sem的參與者,這樣的問題就不存在,對嗎? 因為它適用於2個嘗試寫的客戶端。

如果你們弄清楚我的問題在哪里,那將是非常好的:預先感謝,干杯!

信號量是一個困難的工具,對於普通的用戶空間代碼而言,它的級別太低了。 考慮改用POSIX的控制結構pthread_mutex_tpthread_cond_t 如今,它們可以輕松地用於進程之間的共享內存中。

信號量的主要問題之一是調用可以被任何類型的信號中斷,尤其是在將IO傳遞到您的進程的情況下。 您必須捕獲調用提供的返回值和錯誤代碼,然后再次進入等待狀態。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM