多线程独占访问资源 [英] Exclusive access to resource from multiple threads

查看:72
本文介绍了多线程独占访问资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有与线程的 SIGSTOP 和 SICONT 等效的东西?正在使用 pthread.谢谢

Is there something equivalent to SIGSTOP and SICONT for threads? Am using pthreads. Thanks

我正在线程之间实现一种粗略的文件访问同步形式.因此,如果一个文件已经被一个线程打开,而另一个线程想要再次打开它,我需要在第二个线程执行时停止或暂停第二个线程.当第一个线程完成它的工作时,它会检查其他线程想要使用它释放的文件并唤醒"它们.然后第二个线程从那个点恢复执行.我使用自己的簿记数据结构.

An edit: I am implementing a crude form of file access syncronization among threads. So if a file is already opened by a thread, and another thread wants to open it again, I need to halt or pause the second thread at that point of its execution. When the first thread has completed its work it will check what other threads wanted to use a file it released and "wake" them up. The second thread then resumes execution from exactly that point. I use my own book keeping datastructures.

推荐答案

我会告诉你如何做事而不是回答问题.(查找XY 问题".)

I'm going to tell you how to do things instead of answering the question. (Look up the "X Y problem".)

您试图阻止两个线程同时访问同一个文件.换句话说,访问是互斥的.互斥锁"旨在做到这一点.一般而言,如果您搜索您要执行的操作(防止两个线程同时访问同一资源),而不是搜索您想要执行的操作(让一个线程等待另一个线程),则更容易找到帮助.

You are trying to prevent two threads from accessing the same file at the same time. In other words, access is MUTually EXclusive. A "mutex" is designed to do this. In general, it is easier to find help if you search for what you are trying to do (prevent two threads from accessing the same resource simultaneously) rather than searching for how you want to do it (make one thread wait for the other).

听起来您实际上想要很多读者,但需要一位作家.这可能是第二个最常见的同步问题(在生产者-消费者"问题之后).使用pthread_rwlock:读者调用pthread_rdlock,编写者调用pthread_wrlock.

It sounds like you actually want many readers but one writer. This is probably the second most common synchronization problem (after the "producer-consumer" problem). Use a pthread_rwlock: readers call pthread_rdlock and writers call pthread_wrlock.

如果您正在做如此复杂的事情,您真的应该开始阅读相关文献.如果你认为你可以认真阅读多线程编程,那么你比我聪明得多,你不需要我的帮助.我推荐信号量小书",它可以免费下载(来源).这不是关于 pthreads,但它是好东西.您要问的读写器问题可以在经典同步问题"一章的 §4.2 下找到(哎呀,这个问题甚至在简介中提到过).

If you're doing something this sophisticated, you really should start reading the relevant literature. If you think you can do multithreaded programming some serious reading, you are much smarter than me and you don't need my help. I recommend "The Little Book of Semaphores" which is a free download (source). It's not about pthreads, but it's good stuff. The readers-writers problem you are asking about is found under §4.2 in the chapter "Classical Synchronization Problems" (heck, this problem is even mentioned in the blurb).

多线程编程困难,使用大写字母和粗体.

Multithreaded programing is HARD with capital letters and a bold font.

这篇关于多线程独占访问资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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