如何用Mutex保护向量? [英] How can I protect a vector with a Mutex?

查看:131
本文介绍了如何用Mutex保护向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计一个接受多个不同的交互客户端的C ++服务器,我使用向量来单独跟踪所有的客户端。然而,我意识到,由于有这么多线程运行,有一个很小的机会,一个向量可能被同时读取和写入两个线程。有一个快速和安全的方法来添加一个互斥体或东西给他们,以便它会等待,直到所有的读取完成,直到另一个函数添加到它?没有这样做可以弄乱协议,甚至可能使服务器崩溃。

I am working on designing a C++ server that accepts multiple different interacting clients, and I use vectors to keep track of all of them individually. However, I realized that, because of so many threads running, there's a tiny chance a vector might be read and written to at the same time by two threads. Is there a quick and safe way to add a mutex or something to them so that it will wait until all the reads are done until another function adds to it? Not doing so can mess up the protocol and maybe even crash the server.

我有一个想法,创建一个全局变量,锁定所有读取到一个向量,但我'm不确定是否可以告诉线程互斥排除该变量(即,不将bool更改为false并同时检查为true,使该机制无意义)。

I had an idea to create a global variable that would lock all reads to a vector, but I'm not sure if the threads can be told to mutually exclude that variable too (i.e. not change bool to false and check it as true at the same time, rendering the mechanism pointless).

我使用Windows 7(Visual Studio 2010 Pro)。

I am using Windows 7 (Visual Studio 2010 Pro). Thanks for any and all advice!

推荐答案

由于您使用的是VS2010,因此您应该使用 Concurrency :: concurrent_vector 。但请注意,这个类有限制,并且不是完全线程安全的。您可以使用 Concurrency :: critical_section Concurrency :: reader_writer_lock 。当读取数量多于写入数量时,读写器锁定将提供良好的性能。您还可以使用Windows 本地读写器< a>锁定,但它们只支持Windows Vista和更高版本。

Since you are using VS2010, you should use Concurrency::concurrent_vector. But be aware that there are limitations with this class, and is not fully thread-safe. You may use Concurrency::critical_section or Concurrency::reader_writer_lock. Reader-writer lock would give good performance when there are more reads than writes. You may also use Windows native Reader-writer locks, but they are supported only only Windows Vista and higher.

这篇关于如何用Mutex保护向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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