我正在使用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()
答案 0 :(得分:2)
答案 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!