【发布时间】:2018-04-14 20:54:08
【问题描述】:
我目前正在我的大学学习并发。在这种情况下,我必须在 C 中实现读写器问题,我认为我走在正确的轨道上。
我对这个问题的想法是,我们需要两个锁rd_lock 和wr_lock。当写线程想要更改我们的全局变量时,它会尝试获取两个锁,写入全局并解锁。当读者想要读取全局时,它会检查wr_lock 当前是否被锁定,然后读取该值,但是其中一个读者线程应该获取rd_lock,但其他读者不应该关心rd_lock 是否被锁定锁定。
不允许我使用 pthread 库中已有的实现。
typedef struct counter_st {
int value;
} counter_t;
counter_t * counter;
pthread_t * threads;
int readers_tnum;
int writers_tnum;
pthread_mutex_t rd_lock;
pthread_mutex_t wr_lock;
void * reader_thread() {
while(true) {
pthread_mutex_lock(&rd_lock);
pthread_mutex_trylock(&wr_lock);
int value = counter->value;
printf("%d\n", value);
pthread_mutex_unlock(&rd_lock);
}
}
void * writer_thread() {
while(true) {
pthread_mutex_lock(&wr_lock);
pthread_mutex_lock(&rd_lock);
// TODO: increment value of counter->value here.
counter->value += 1;
pthread_mutex_unlock(&rd_lock);
pthread_mutex_unlock(&wr_lock);
}
}
int main(int argc, char **args) {
readers_tnum = atoi(args[1]);
writers_tnum = atoi(args[2]);
pthread_mutex_init(&rd_lock, 0);
pthread_mutex_init(&wr_lock, 0);
// Initialize our global variable
counter = malloc(sizeof(counter_t));
counter->value = 0;
pthread_t * threads = malloc((readers_tnum + writers_tnum) * sizeof(pthread_t));
int started_threads = 0;
// Spawn reader threads
for(int i = 0; i < readers_tnum; i++) {
int code = pthread_create(&threads[started_threads], NULL, reader_thread, NULL);
if (code != 0) {
printf("Could not spawn a thread.");
exit(-1);
} else {
started_threads++;
}
}
// Spawn writer threads
for(int i = 0; i < writers_tnum; i++) {
int code = pthread_create(&threads[started_threads], NULL, writer_thread, NULL);
if (code != 0) {
printf("Could not spawn a thread.");
exit(-1);
} else {
started_threads++;
}
}
}
目前,当使用 1 个读取器和 1 个写入器运行时,它只会打印很多零,这意味着它从未真正执行写入器线程中的代码。我知道这不会像预期的那样与多个阅读器一起工作,但是当每个阅读器运行它时,我不明白出了什么问题。
【问题讨论】: