首页 > 解决方案 > Objective C++,如何在后台线程中使用runloop?

问题描述

大编辑:我认为这个问题可以简化为——如何在后台线程中运行 corebluetooth 并初始化 CBCentralManager?谢谢!

我正在使用通过命令行运行的 CoreBluetooth 制作一个客观的 C++ 应用程序,因此对象 C 部分需要显式调用 runloop [see this]。CoreBluetooth 要求有一个活动的运行循环,以便执行回调。下面的代码在程序开始时调用 runloop 以使一切正常:

实现.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++ 主方法进行异步调用:

主文件

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 文件中创建一个新线程,然后调用线程的当前运行循环:

实现.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]]))
    {} 


}

但这只是提前终止。不确定我的方法是否存在根本性的问题。再次——我想在后台线程中运行我的目标 C 代码,并在主线程中运行我的 c++ 代码。

谢谢!

实际上等等,这个解决方案没有在后台线程中正确地创建一个运行循环

我的问题之一是让 runloop 在后台线程中运行。 主文件

int main() {
  std::thread worker(run_cpp_in_thread);

}

implementation.mm // 在 init 方法的某个地方

NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop run];

现在的问题是CoreBluetooth 在中央管理器开机后立即退出。似乎与框架和线程有关。

标签: c++objective-cmultithreadingcore-bluetoothnsrunloop

解决方案


我相信您要求 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
}

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


推荐阅读