STL线程安全的解决方法

Multithreading Issues
STL is not thread protected, so you must provide locks on your collections if
they will be used in multithreaded environment.
The standard locking mechanisms of Mutexes, Semaphores and Critical Sections can be used. One simple mechanism for providing locking is to declare a lock class. In this class the constructor creates the lock, and the destructor destroys the lock.
Then provide lock() and unlock() methods. For example:

 

class Lock
{
public:
 HANDLE    _hMutex;            // used to lock/unlock object      
 Lock() : _hMutex(NULL) 
 { _hMutex = ::CreateMutex( NULL, false,NULL) ); } 

 virtual ~Lock() { ::CloseHandle( _hMutex ); }      
 bool lock () 
 {  
  if ( _hMutex == NULL )   
   return false;  
  WaitForSingleObject( _hMutex, INFINITE );  
  return true; 
 }      
 void unlock ()
 { ReleaseMutex(_hMutex); }    
};

 

Then declare a class that is derived from one of the STL collections,
and in the class override the access methods to the collection that might cause an insertion or deletion of an element.
For example a general vector class would be:

 

template <class T>
class LockVector : vector<T>, Lock
{
public: LockVector () : vector<T>(), Lock() {} 
  virtual LockVector () {}      
  void insert ( T & obj ) 
  {  
   if ( !lock())   
    return;  
   vector<T>::push_back (obj);  
   unlock(); 
  }
};

STL(Standard Template Library)是C++标准库中的一个重要组成部分,提供了一系列的容器类,如vector、list、map等。STL容器本身并不是线程安全的,也就是说,在多线程环境下同时对同一个容器进行读写操作可能会导致数据竞争和不确定的结果。 然而,C++标准库并没有提供原生的线程安全STL容器。如果需要在多线程环境下使用STL容器,可以考虑以下几种方式: 1. 互斥锁(Mutex):使用互斥锁来保护对STL容器的读写操作。在每次访问容器之前,先获取互斥锁,操作完成后释放锁。这样可以确保同一时间只有一个线程能够对容器进行操作,从而避免数据竞争。 2. 读写锁(Read-Write Lock):使用读写锁来实现对STL容器的读写操作。读写锁允许多个线程同时读取容器,但只有一个线程能够进行写操作。这样可以提高读取性能,但写操作仍然需要互斥保护。 3. 并发容器:一些第三方库或框架提供了线程安全STL容器的实现,如Intel TBB(Threading Building Blocks)库中的concurrent_vector、concurrent_map等。这些容器在内部使用了锁或其他机制来保证线程安全性。 需要注意的是,使用线程安全STL容器并不能完全解决多线程编程中的所有并发问题,仍然需要合理地设计和管理线程间的同步与通信。此外,使用锁或其他同步机制可能会引入额外的开销和复杂性,需要权衡使用的场景和性能需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值