我想知道是否有可能改变读者和作家的问题,以便作家成为增量和减量者?我的计划是使用pthreads创建随机数量的增量器,减量器和读取器线程,然后在计数器中保持运行总计,这样每当增量器访问数据时,计数器就会增加1,反之亦然。因此,为了解释,代码将以与读者和作者相同的方式工作,其中作者获得对数据的独占访问权。但是线程会为作者打印出来 - 无论是增量器还是减量器,以及存储在计数器中的当前值。对于读者 - 当该线程访问它时存储在计数器中的值。
这是我目前的代码,但它显然不会影响单独的增量器和减量器。
#include <signal.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include "sem_ops.h"
#define READERS 8
#define WRITERS 3
int counter = 0;
int readers = 0;
int reader_sem;
int counter_sem;
void *writerfunc( void * arg ) {
int *me;
me = (int *) arg;
srand( time( NULL ) );
sleep( rand() % 5 );
P( counter_sem );
counter++;
printf( "Writer Thread %d running!! counter = %d\n", *me, counter );
V( counter_sem );
pthread_exit( NULL );
}
void *readerfunc( void * arg ) {
int *me;
me = (int *) arg;
P( reader_sem );
readers++;
if( readers == 1 )
P( counter_sem );
V( reader_sem );
srand( time( NULL ) );
sleep( rand() % 5 );
printf( "Reader Thread %d running!! counter = %d\n", *me, counter );
P( reader_sem );
readers--;
if( readers == 0 )
V( counter_sem );
V( reader_sem );
pthread_exit( NULL );
}
int main( void ) {
int i;
pthread_t rtid[READERS];
int readerid[READERS];
pthread_t wtid[WRITERS];
int writerid[WRITERS];
counter = 0;
reader_sem = semtran( IPC_PRIVATE );
counter_sem = semtran( IPC_PRIVATE );
V( counter_sem );
V( reader_sem );
for( i=0; i<READERS; i++ )
readerid[i] = i;
for( i=0; i<WRITERS; i++ )
writerid[i] = i;
for( i=0; i<WRITERS; i++ )
pthread_create( &wtid[i], NULL, writerfunc, (void *) &writerid[i] );
for( i=0; i<READERS; i++ )
pthread_create( &rtid[i], NULL, readerfunc, (void *) &readerid[i] );
for( i=0; i<WRITERS; i++ )
pthread_join( wtid[i], NULL );
for( i=0; i<READERS; i++ )
pthread_join( rtid[i], NULL );
return 0;
}
我只是想知道这是否可行,如果有的话,任何关于如何更新我的代码的提示都会非常感激。谢谢!