目标C++,如何在后台线程中使用运行循环?

Objective C++, how to use runloop in background thread?

本文关键字:运行 循环 线程 后台 C++ 目标      更新时间:2023-10-16

大编辑:我认为这个问题可以简化为--如何在后台线程中运行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
}

您仍然需要正确处理加入,否则会使您的应用程序无响应/崩溃