简体   繁体   中英

C pthreads: Start a Thread from main

I am using an ARM processor with an Embedded Linux (C). 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.

I thought to outsource the Bluetooth data transfer to a POSIX Thread. In the main function I have now to trigger the Thread to perform the sending of the data. 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.

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) .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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