使用 pthreads 在 C 中并发读取器和相互排除写入器 [英] concurrent readers and mutually excluding writers in C using pthreads

查看:35
本文介绍了使用 pthreads 在 C 中并发读取器和相互排除写入器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有人可以转发我或向我展示一个程序,它有多个读者,但在 C 中相互排斥作者.我在整个互联网上搜索了它,但找不到一个使用粗粒度显示这种行为的示例锁定.我知道我可以使用 pthread_rwlock_init、pthread_rwlock_rdlock 等,我只是不知道如何使用它.我通过例子学习,这就是我在这里的原因.

I was hoping if someone could forward me or show me a program that has multiple readers yet mutually excluding writers in C. I searched the entire internet for it, and could not find a single example that displays this behavior using coarse-grained locking. I know I can use pthread_rwlock_init, pthread_rwlock_rdlock, etc, I just don know how to use it. I learn by examples, which is why Im here.

假设我有一个代码区域(不是共享变量)并且我想要多次读取,但只有一个写入器,这就是我不知道如何使用 pthreads rwlocks 来完成的.我不明白代码如何知道现在正在写入,而不是现在正在读取.谢谢.

Suppose I have a region of code(not a shared variable)and I want multiple reads, yet a single writer, this is what I don't know how to accompolish using pthreads rwlocks. I don't understand how the code will know that now it is being written to, compared to now it is being read. Thanks.

推荐答案

您可以查看 Peter Chapin 的 Pthread 教程 示例.我在下面添加了它.

You can take a look at page 24 of Peter Chapin's Pthread Tutorial for an example. I added it below.

#include<pthread.h>
int shared;
pthread_rwlock_t lock ;
void∗ thread_function (void∗ arg)
{
  pthread_rwlock_rdlock (&lock);
  //Read from the shared resource.
  pthread_rwlock_unlock(&lock);
}
void main( void )
{
  pthread_rwlock_init(&lock, NULL);
  // Start threads here.
  pthread_rwlock_wrlock(& lock );
  // Write to the shared resource .
  pthread_rwlock_unlock(&lock);
  // Join_with threads here .
  pthread_rwlock_destroy(&lock);
  return 0 ;
}

这篇关于使用 pthreads 在 C 中并发读取器和相互排除写入器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆