我已經寫了一個讀寫器鎖實現,我打算做的是爲每個線程設置回調。假設我們有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);
}
在pthreads中查找條件變量 –
您可以通過信號實施互斥,但也可以考慮使用爲相互設計的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
下面是[條件變量]的一個很好的解釋(https://computing.llnl.gov/tutorials/pthreads/#ConditionVariables)。 – e0k