Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 242
BGWH Avatar asked Dec 28 '25 20:12

BGWH


1 Answers

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

like image 142
Sergey L. Avatar answered Dec 30 '25 14:12

Sergey L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!