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

问题描述 投票:0回答:2

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

[FATAL:flutter/shell/common/shell.cc(808)] Check failed: task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread(). 

来自此行:

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

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

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

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

我跟踪了task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()调用,结果以这个结尾:

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

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

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

class Object{
public:
  void run() {
  //how can this run function know it's being called by t thread instead of main's thread?
  }
}


int main() {
  Object obj;
  std::thread t (obj.run);
  RunLoop();
}
c++ flutter
2个回答
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!

2
投票

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

Linux

Windows

[在C++11中被标准化为跨平台解决方案

© www.soinside.com 2019 - 2024. All rights reserved.