C ++如何检测正在运行的当前线程?

时间:2019-10-20 22:09:21

标签: c++ flutter

我正在使用Flutter for Desktop,并且正在从单独的线程中调用引擎上的方法。我收到此错误:

https://www.genecards.org/gene/api/data/Enhancers?geneSymbol=BSCL2

来自此行:

https://github.com/flutter/engine/blob/master/shell/common/shell.cc#L836

我确认当我从创建引擎的同一线程中调用该方法时,不会发生错误。

所以错误告诉我,我需要在创建引擎的同一线程中调用此方法

那么C ++如何知道哪个线程正在调用方法?

我跟踪了[FATAL:flutter/shell/common/shell.cc(808)] Check failed: task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread(). 调用,结果如下:

https://github.com/flutter/engine/blob/master/fml/task_runner.cc#L41

但是我不明白发生了什么。

因此,以简单的代码表示,假设我们有:

task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()

2 个答案:

答案 0 :(得分:2)

大多数支持多线程的OS都有系统调用来获取当前线程的线程ID。

Linux

Windows

C++11中将其标准化为跨平台解决方案

答案 1 :(得分:2)

您可以获取在构造函数中创建对象的线程ID,然后将其与调用函数的当前线程ID进行比较。

为了更具体一点,我制作了一个类DetectsWhenOnDifferentThread,当您从与其构造时所用的线程不同的线程中调用其DoThing函数时,该类将输出不同的内容。

#include <thread>
#include <iostream>

class DetectsWhenOnDifferentThread {
 public:
  DetectsWhenOnDifferentThread()
      : thread_id_on_construction_(std::this_thread::get_id()) {}
  void DoThing() {
    if (std::this_thread::get_id() != thread_id_on_construction_) {
      std::cout << "I'm on the wrong thread!" << std::endl;
    } else {
      std::cout << "Thanks for using me on the proper thread." << std::endl;
    }
  }
  std::thread::id thread_id_on_construction_;
};

void ManipulateThing(DetectsWhenOnDifferentThread* thingy) {
  thingy->DoThing();
}

int main() {
  DetectsWhenOnDifferentThread thingy;
  thingy.DoThing();
  auto worker = std::thread(ManipulateThing, &thingy);
  worker.join();
}

下面是编译并运行代码的示例:

$ g++ --version
g++ (Debian 9.2.1-8) 9.2.1 20190909
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ g++ -pthread ex.cc

$ ./a.out
Thanks for using me on the proper thread.
I'm on the wrong thread!