2016-01-22 26 views
-1

我已經寫了一個讀寫器鎖實現,我打算做的是爲每個線程設置回調。假設我們有3個讀取器線程,其中3個讀取了值X.現在,寫入器線程將值X更新爲X + 100。這應該將回調發送到值已更改的所有3個讀取器線程。我們如何在C編程語言的多線程環境中實現這樣的回調?如何在讀寫器多線程程序中設置回調

#include<stdio.h> 
#include<stdlib.h> 
#include<pthread.h> 
#include<semaphore.h> 
#include<stdint.h> 

sem_t dbAccess; 
sem_t readCountAccess; 

int readCount=0; 

void *Reader(void *arg); 
void *Writer(void *arg); 

int main(int argc, char* argv[]) 
{ 
    int i=0, num_of_readers = 0, num_of_writers = 0; 

    //inititalizing semaphores                                             
    sem_init(&readCountAccess,0,1); 
    sem_init(&dbAccess,0,1); 

    pthread_t readers_tid[100], writer_tid[100]; 
    num_of_readers = atoi(argv[1]); 
    num_of_writers = atoi(argv[2]); 

    for(i = 0; i < num_of_readers; i++) 
    { 
     pthread_create(&readers_tid[i], NULL , Reader, (void *) (intptr_t) i); 
    } 

    for(i = 0;i < num_of_writers; i++) 
    { 
     pthread_create(&writer_tid[i], NULL, Writer, (void *) (intptr_t) i); 
    } 

    for(i = 0; i < num_of_writers; i++) 
    { 
     pthread_join(writer_tid[i],NULL); 
    } 

    for(i = 0; i < num_of_readers; i++) 
    { 
     pthread_join(readers_tid[i], NULL); 
    } 

    sem_destroy(&dbAccess); 
    sem_destroy(&readCountAccess); 
    return 0; 
} 

void * Writer(void *arg) 
{ 

    sleep(1); 
    int temp=(intptr_t) arg; 
    printf("Writer %d is trying to enter into database for modifying the data\n",temp); 
    sem_wait(&dbAccess); 
    printf("Writer %d is writting into the database\n",temp); 
    printf("Writer %d is leaving the database\n"); 
    sem_post(&dbAccess); 
} 

void *Reader(void *arg) 
{ 
    sleep(1); 
    int temp=(intptr_t) arg; 
    printf("Reader %d is trying to enter into the Database for reading the data\n",temp); 
    sem_wait(&readCountAccess); 
    readCount++; 
    if(readCount==1) 
    { 
     sem_wait(&dbAccess); 
     printf("Reader %d is reading the database\n",temp); 
    } 
    sem_post(&readCountAccess); 
    sem_wait(&readCountAccess); 
    readCount--; 
    if(readCount==0) 
    { 
     printf("Reader %d is leaving the database\n",temp); 
     sem_post(&dbAccess); 
    } 
    sem_post(&readCountAccess); 
} 
+1

在pthreads中查找條件變量 –

+0

您可以通過信號實施互斥,但也可以考慮使用爲相互設計的pthread [mutex](https://computing.llnl.gov/tutorials/pthreads/#Mutexes)鎖排除,並具有特定的功能只是爲了這一點。他們來自稍後的[標準](https://en.wikipedia.org/wiki/POSIX#Parts_before_1997)(1003.1c-1995,而不是1003.1b-1993中的信號量)。 – e0k

+0

下面是[條件變量]的一個很好的解釋(https://computing.llnl.gov/tutorials/pthreads/#ConditionVariables)。 – e0k

回答

0

我可以看到2種可能的方法:
1.讓讀者調用一個函數時,他們希望得到通知。作者必須標記每個讀者線程的內容,說他們必須在共享變量上調用您的CB。這將是我的首選方法,因爲我設計讀者知道他們何時需要這些更新。
2.指示讀者讓他們從信號處理程序執行一些代碼。您可以使用SIG_USR1/2,並在某處添加一些額外標記以瞭解更改內容和要調用的內容。這顯然不那麼幹淨,但我想當第三方創建這些線程時會更方便,並且無法控制他們在做什麼。

HTH

編輯

我忘了另一個重要的事情 - 如果你只更新POD變量(INT等),你可以使用方法1與順序鎖和每一個本地副本讀者線程。這樣每個讀者都會知道價值的變化。

另一個考慮是你需要讀者只知道最後的價值,還是他們需要回應每一個變化?如果你需要響應每一個變化,你可以使用一個無鎖隊列,每個讀者一個,並讓作者推入其中的每一個。

相關問題