Multithreading 如何在C++;/CLI?

Multithreading 如何在C++;/CLI?,multithreading,c++-cli,Multithreading,C++ Cli,为了简化我的问题,我有一个多线程来访问包含对象句柄的单个数据结构。我希望能够做到的是,如果其中一个线程当前正在读写一个对象,那么能够从可能访问数据结构中该对象的其他线程锁定该对象 看起来是这样的: ref class ThreadX{ public: ThreadX(List<customer^>^ aList){ this->customerDatabase = aList; } void ThreadProc(){ /

为了简化我的问题,我有一个多线程来访问包含对象句柄的单个数据结构。我希望能够做到的是,如果其中一个线程当前正在读写一个对象,那么能够从可能访问数据结构中该对象的其他线程锁定该对象

看起来是这样的:

ref class ThreadX{
public:
    ThreadX(List<customer^>^ aList){
        this->customerDatabase = aList;
    }
    void ThreadProc(){
        // do something with thread
    }
}
private:
List<customer^>^ customerDatabase;

int main(){
    List<customer^>^ aList;
    ThreadX^ process1 = gcnew ThreadX(aList);

    Thread^ Thread1 = gcnew Thread(gcnew ThreadStart(process1, &ThreadX::ThreadProc));
    Thread1->Name = "Thread 1";
    Thread^ Thread2 = gcnew Thread(gcnew ThreadStart(process1, &ThreadX::ThreadProc));
    Thread2->Name = "Thread 2";
    Thread1->Start();
    Thread2->Start();
}
ref class ThreadX{
公众:
ThreadX(列表^aList){
此->customerDatabase=aList;
}
void ThreadProc(){
//用线做点什么
}
}
私人:
列表^customerDatabase;
int main(){
列表列表;
ThreadX^process1=gcnewthreadx(列表);
Thread^Thread1=gcnewthread(gcnewthreadstart(process1,&ThreadX::ThreadProc));
Thread1->Name=“Thread 1”;
Thread^Thread2=gcnewthread(gcnewthreadstart(process1,&ThreadX::ThreadProc));
Thread2->Name=“Thread2”;
Thread1->Start();
Thread2->Start();
}
现在我将有多个线程,但我希望能够拒绝一个线程访问
customerDatabase
的索引。我曾读到,我应该能够做到这一点与锁,但我有一个困难的时间来计算它。我看到的大部分是C#而不是C++/CLI。我删掉了很多代码,使其更具可读性,而不仅仅是一堆代码。

C#lock关键字只是监视器的包装。C++\CLI示例如下链接所示:

我已经复制了下面的相关代码

void Enqueue(T qValue)
{
  // Request the lock, and block until it is obtained.
  Monitor::Enter(m_inputQueue);
  try
  {
     // When the lock is obtained, add an element.
     m_inputQueue->Enqueue(qValue);
  }
  finally
  {
     // Ensure that the lock is released.
     Monitor::Exit(m_inputQueue);
  }
};
C#lock关键字只是监视器的包装。C++\CLI示例如下链接所示:

我已经复制了下面的相关代码

void Enqueue(T qValue)
{
  // Request the lock, and block until it is obtained.
  Monitor::Enter(m_inputQueue);
  try
  {
     // When the lock is obtained, add an element.
     m_inputQueue->Enqueue(qValue);
  }
  finally
  {
     // Ensure that the lock is released.
     Monitor::Exit(m_inputQueue);
  }
};

atomic应该具备您所需要的功能。如果您可以访问C++11功能(没有使用CLI,不确定是否使用CLI),那么我会在Anthony Williams的《C++并发操作》一书中搜索线程安全链表实现。您正在以一种非常非建设性的方式考虑这一点。无法锁定对象,只能使用锁定来阻止代码。很重要的一点是,你要自学,否则线程会把你活活吃掉。我相信std::atomic与C++/CLI不兼容。std::atomic应该具备你所需要的功能。如果你可以使用C++11功能(没有使用CLI,不确定是否使用CLI),那么我会在Anthony Williams的书中搜索线程安全链表实现“C++并发运行”您是以一种非常非建设性的方式来考虑这一点的。不可能锁定对象,您只能使用锁来阻止代码。非常重要的是,您必须自学,否则线程将活活吃掉您。我相信std::atomic与C++/CLI不兼容。