Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Multithreading 从Windows线程库到C++;11_Multithreading_C++11 - Fatal编程技术网

Multithreading 从Windows线程库到C++;11

Multithreading 从Windows线程库到C++;11,multithreading,c++11,Multithreading,C++11,我想删除旧代码中线程处理方式的一些Windows依赖项,如何将这段代码转换为C++11线程方式 MyClass运行方法: void MyClass::run() { while(true) { WaitForSingleObject(startEvent, INFINITE); processData(); ResetEvent(startEvent); SetEvent(hEvent); } } 另一

我想删除旧代码中线程处理方式的一些Windows依赖项,如何将这段代码转换为C++11线程方式

MyClass运行方法:

void MyClass::run()
{
    while(true)
    {
        WaitForSingleObject(startEvent, INFINITE);

        processData();

        ResetEvent(startEvent);
        SetEvent(hEvent);
    }
}
另一类中的主更新:

{
    .
    .
    .
    WaitForSingleObject(myClassInstance.hEvent, INFINITE);
    ResetEvent(myClassInstance.hEvent);

    // Getting data processed by myClassInstance in the previous update call
    // Mem copies to myClassInstance to be used later by myClassInstance processData()

    SetEvent(myClassInstance.startEvent);
    .
    .
    .
}

您可以使用
std::condition\u变量和
bool
轻松创建事件类:

class Event {
  std::condition_variable cv_;
  std::mutex mtx_;
  bool signaled_ = false;

public:
  void wait() {
    std::unique_lock<std::mutex> lock{mtx_};
    while (!signaled_) {
      cv_.wait(lock);
    }
  }

  void reset() {
    std::lock_guard<std::mutex> lock{mtx_};
    signaled_ = false;
  }

  void set() {
    {
      std::lock_guard<std::mutex> lock{mtx_};
      signaled_ = true;
    }
    cv_.notify_one();
  }
};

Aweson Casey,它工作得很好,我以为它会更复杂一点,但实际上不是,你只需要知道C++11线程库是如何工作的,谢谢!(对不起,不能投票支持你的答案,我需要15分的声誉!)
struct MyClass {
  Event start;
  Event ready;

  void processData();
  void run();
};

void MyClass::run() {
  while (true) {
    start.wait();

    processData();

    start.reset();
    ready.set();
  }
}

void main_update_in_another_class() {
  ready.wait();
  ready.reset();

  // Getting data processed by myClassInstance in the previous update call
  // Mem copies to myClassInstance to be used later by myClassInstance processData()

  start.set();

  // Do other things that don't require access to myClassInstance
}