SlimReaderWriter(SRW)锁定数组(使用new运算符)

时间:2012-08-05 06:15:17

标签: multithreading visual-c++ locking

也许这听起来很愚蠢,但我想在运行时动态创建一个SRWLocks矢量/数组。以下代码编译两种方式,但数组的东西不起作用。可能问题应该是,我可以使用new运算符创建一个SRWLock对象吗?

如果不是这样做的话,创建SRWLock对象数组的正确方法是什么?

#include "stdafx.h"
#include <ppl.h>
#include <Windows.h>
#include <iostream>

using namespace std;

#define NOT_WORKING

int _tmain(int argc, _TCHAR* argv[])
{


#ifdef NOT_WORKING

// The following doesn't work
       SRWLOCK *lock = new SRWLOCK[2];

       int a = 10;

       AcquireSRWLockExclusive(&lock[0]);
       cout<<"Exclusive Lock Acquired";
       a++;
       ReleaseSRWLockExclusive(&lock[0]);


       // The following doesn't work either

       /*
       SRWLOCK *lock_n = new SRWLOCK;


       AcquireSRWLockExclusive(lock_n);
       cout<<"Exclusive Lock Acquired";
       a++;
       ReleaseSRWLockExclusive(lock_n);

       */

       #else
// This works
       SRWLOCK lock;

       int a = 10;
       AcquireSRWLockExclusive(&lock);
       cout<<"Exclusive Lock Acquired";
       a++;
       ReleaseSRWLockExclusive(&lock);

#endif
       cout<<"Value of a:"<<a;
       cin.get();

       return 0;
}

1 个答案:

答案 0 :(得分:0)

User1577008自己的答案: 得到它了!在动态创建锁定对象时,需要使用InitializeSRWLock()函数。有人粘贴这个答案,并帮我解决这个问题。