目标C++,如何在后台线程中使用运行循环?
Objective C++, how to use runloop in background thread?
大编辑:我认为这个问题可以简化为--如何在后台线程中运行core蓝牙并初始化CBCentralManager?谢谢!
我正在用 CoreBluetooth 制作一个通过命令行运行的客观 c++ 应用程序,因此对象 C 部分需要显式调用 runloop[请参阅此处]。核心蓝牙要求有一个活动的运行循环,以便执行回调。下面的代码在程序开始时调用 runloop 以使一切正常:
implementation.mm
// inside init method
// initialize bluetooth manager, must initialize before the runloop
self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
// start run loop
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
while(([runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]))
{}
我可以从我的 c++ main 方法进行异步调用:
主.cpp
int main() {
std::thread worker(do_cpp_things); // c++ things in background thread
run_objective_c_code(); // call objective c code using main thread
}
但是,使用这种方法,我的c ++部分必须在后台线程中运行。 目标 C 应用程序位于主线程中,这与我想要的相反。所以我尝试在目标 C 文件中创建一个新线程,然后调用线程的当前运行循环:
implementation.mm
// start a new thread
-(void)startThread {
NSThread *A = [[NSThread alloc] initWithTarget:self selector:@selector(runTheLoop) object:nil]; //create thread A
[A start];
}
// call runloop while in new thread
-(void) runTheLoop {
// Commenting out initialization for the sake of simplicity before it terminates when trying to initialize the manager in this example
// self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
// TERMINATES HERE
while(([runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]))
{}
}
但这只是提前结束。不确定我的方法是否存在根本性错误。再次 - 我想在后台线程中运行我的 objective-C 代码,使用活动的运行循环和在主线程中运行我的 c++ 代码。
谢谢!
实际上等待,此解决方案无法在后台线程中正确创建运行循环:
我的一个问题是让运行循环在后台线程中运行。主.cpp
int main() {
std::thread worker(run_cpp_in_thread);
}
implementation.mm//在初始化方法中的某个地方
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop run];
现在的问题是 核心蓝牙 在打开中央管理器电源后立即退出.似乎与框架和线程有关。
我相信您要求c ++在后台运行的线程中运行。 相反,只需按 C 函数在后台运行
int main() {
std::thread worker(run_objective c function); // objective c in background thread
do_cpp_things; // call c++ things code using main thread
}
您仍然需要正确处理加入,否则会使您的应用程序无响应/崩溃
相关文章:
- 循环无限运行C++解决骑士之旅问题
- 我的代码运行良好,但在游戏循环中中断
- 如何根据用户在C++中的输入运行不同数量的 for 循环
- 我可以根据用户输入在运行时生成"循环"吗?
- 重新启动后,线程无法在 while 循环中再次运行
- 运行无限循环的最小二叉树问题
- 目标C++,如何在后台线程中使用运行循环?
- 如何在指定的时间内运行循环
- 苹果运行循环的回调方法
- 我怎样才能一直运行循环,直到按下键 (C++)
- 如何在C++中每次运行循环时将变量递增1`
- 如何在第一次运行循环时忽略代码的特定部分
- 如何在每次运行循环时更改for循环中的对象
- 应用程序在访问主运行循环时崩溃 (SIGABRT)
- osX :运行循环选项(创建事件点击时)
- 线程如何运行循环直到连接
- 在指定时间运行c++循环
- 在运行循环外声明、分配和释放线程局部指针变量
- 这是在c++中运行循环的有效方式吗?
- 如何在qt中使用gui对象名运行循环