C++线程和简单的阻塞机制?
我有一个 C++ 程序,它运行一堆线程来操作相同的数据。每个线程都有一个指向正在操作的对象的指针,例如:
thread1 和 thread2 都有一个指向 object1 的指针
object1->addSomething() 可以由线程 1 或线程 2 使用并引用同一个对象
现在,如果两个线程同时执行这些操作可能会带来一些麻烦,所以我需要一个简单的阻塞机制。我想要的很简单:
void method()
{
waitUntilFree()
blockForOthers()
doSomething()
unblock()
}
有没有一种简单的方法可以做到这一点?我只想阻止并等待它空闲。我不介意线程可能需要等待一段时间。有一个简单的机制可以做到这一点吗?我对这些线程使用 Boost,但我一生都无法找到一种方法来完成这个(看似)简单的阻塞和等待事情。
I have a program in C++ that runs a bunch of threads to manipulate the same data. Each of these threads have a pointer to an object that is being manipulated, for example:
thread1 and thread2 both have a pointer to object1
object1->addSomething() can be used by either thread1 or 2 and refer to the same object
Now, these operations might give some trouble if they are being done at the same moment by both threads, so I want a simple mechanism for blocking. What I want is simply this:
void method()
{
waitUntilFree()
blockForOthers()
doSomething()
unblock()
}
Is there a simple way to do this? I just want to block and wait until it is free. I don't mind that the thread might have to wait a while. Is there an easy mechanism to do this? I use Boost for these threads but I couldn't for the life of me figure out a way to do this (seemlingly) simple block-and-wait thing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如 Ferruccio 所指出的,您可以使用 Mutex 就像
Boost.Mutex
来自同一个库进行同步:As noted by Ferruccio you can use a Mutex like
Boost.Mutex
from the same library for synchronization:由于您已经在使用 Boost,因此可以使用 增强互斥体以保护多个线程同时访问。
然后在每个线程上使用 join() 等待其完成。
Since you're already using Boost, you can use a Boost mutex to protect simultaneous access by multiple threads.
Then use a join() on each thread to wait for it to complete.
使用互斥体。
有关它的更多信息,您可以在 http://www.yolinux.com/TUTORIALS/ 找到LinuxTutorialPosixThreads.html#SYNCHRONIZATION
Use mutex.
More information about it you can find at http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html#SYNCHRONIZATION
您正在寻找所谓的互斥体。它们是线程库的一部分。看看 这位博士。多布斯文章。
You are looking for so-called mutexes. These come as part of the thread library. Have a look at this dr. dobbs article.