简体   繁体   English

C pthreads:从main开始一个线程

[英]C pthreads: Start a Thread from main

I am using an ARM processor with an Embedded Linux (C). 我正在使用带有嵌入式Linux(C)的ARM处理器。 My main program has to perform real-time operations and after a certain time duration (determined by the main program) I have to send data via a Bluetooth connection to an Android Tablet. 我的主程序必须执行实时操作,并在一段时间后(由主程序确定)我必须通过蓝牙连接将数据发送到Android平板电脑。

I thought to outsource the Bluetooth data transfer to a POSIX Thread. 我想将蓝牙数据传输外包给POSIX线程。 In the main function I have now to trigger the Thread to perform the sending of the data. 在main函数中,我现在要触发Thread来执行数据发送。 So how can I 'restart' a Thread, because it should just send data via Bluetooth when the main function has to do it? 那么我怎么能'重启'一个线程,因为它应该只在主要功能必须通过蓝牙发送数据? That's why it also doesn't help to have a loop in the Thread function (combined with a sleep function) because, as I have already said, the timing is determined by the main function not the Thread function itself. 这就是为什么它也没有帮助在Thread函数中有一个循环(与sleep函数结合),因为正如我已经说过的,时间由main函数决定,而不是Thread函数本身。

So is there an option to restart the Thread? 那么有没有重启线程的选项? Or maybe if anyone has a better idea to solve this issue I am open to it. 或者,如果有人有更好的想法来解决这个问题,我愿意接受它。 :) :)

The easiest is with a synchronisation routine. 最简单的是使用同步例程。 Semaphore comes to mind: 信号量浮现在脑海中:

thread() {
    for (;;) {
        sem_wait(&semaphore);
        send_data(...);
    }
}

main() {
    get_data();
    pus_data_in_a_buffer();
    sem_post(&semaphore);
    // ...
}

But if all you need to do is asynchronously send data you may want to have a look at the asynchronous IO library aio(7) . 但是,如果您只需要异步发送数据,您可能需要查看异步IO库aio(7)

It is possible for you to just have your thread loop, check if the send buffer is ready to send, and then pause briefly if it isn't ready. 您可以只进行线程循环,检查发送缓冲区是否准备好发送,然后如果没有准备就暂停。 While not ideal for every circumstance, you certainly can let the thread keep looping and waiting for something to do. 虽然不是每种情况都不理想,但你当然可以让线程保持循环并等待某些事情要做。

Note that this is not practical for every case, but because you have mentioned that it is a real-time scenario, this may be your best option for maintaining peak performance, as semaphores can be somewhat expensive (in terms of processing time). 请注意,这对于每种情况都不实用,但是因为您已经提到它是实时场景,这可能是保持峰值性能的最佳选择,因为信号量可能有些昂贵(就处理时间而言)。 If you do not need such optimization, you are probably safer using semaphores. 如果您不需要这样的优化,那么使用信号量可能更安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM