我正在考虑如何实现一个包含私有数据的类,这些私有数据将最终由多个线程通过方法调用进行修改。对于同步(使用Windows API),我计划使用一个对象,因为所有线程都将从同一个进程产生。从多个线程同步方法调用共享对象
鉴于以下设计,我有几个问题。
template <typename T> class Shareable
{
private:
const LPCRITICAL_SECTION sync; //Can be read and used by multiple threads
T *data;
public:
Shareable(LPCRITICAL_SECTION cs, unsigned elems) : sync{cs}, data{new T[elems]} { }
~Shareable() { delete[] data; }
void sharedModify(unsigned index, T &datum) //<-- Can this be validly called
//by multiple threads with synchronization being implicit?
{
EnterCriticalSection(sync);
/*
The critical section of code involving reads & writes to 'data'
*/
LeaveCriticalSection(sync);
}
};
// Somewhere else ...
DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
Shareable<ActualType> *ptr = static_cast<Shareable<ActualType>*>(lpParameter);
T copyable = /* initialization */;
ptr->sharedModify(validIndex, copyable); //<-- OK, synchronized?
return 0;
}
我看到它的方式,API调用将在当前线程的上下文中进行。也就是说,我认为这与我从指针中获取临界区对象并从ThreadProc()
内调用API相同。但是,我担心如果该对象被创建并放置在主/初始线程中,那么API调用将会有些奇怪。
- 当
sharedModify()
称为同一对象上同时, 从多个线程,将所述同步是隐含的,在I中描述它上面的 方式吗? - 我是否应该得到一个指向 临界区对象的指针并使用它?
- 是否还有其他一些 更适合这种情况的同步机制?