0
$\begingroup$

Rosanswers logo

I am trying to stop two threads from within a while loop but it doesn't stop on the Ctrl+C (SIGINT).How do I terminate the threads on receiving Ctrl+C from CLI? Would an AsyncSpinner help me here? I do not understand the syntax implementation of AsyncSpinner, specifically how to assign a method to a thread spun by it (as I have been able to do with std::threads below).

void Listener::spin(int sockfd){

int n;
sock_fd_ = sockfd;
ros::Rate loop_rate(MESSAGE_FREQ);      // set the rate as defined in the macro MESSAGE_FREQ

while(ros::ok) {          

    loop_rate.sleep();

    std::thread t_write(&Listener::getMessageValue, this); //writes data onto tcp socket
    std::thread t_read(&Listener::readBuffer, this);  // reads data from tcp socket

    t_write.join();
    t_read.join();        
    
    ros::spinOnce();
        
   }  

   n = close(sock_fd_);
         
}

This is being called in the main like this:

int main(int argc, char *argv[]) {
     .... 
    listener.spin(sockfd);
    return 0;
}

Originally posted by curi_ROS on ROS Answers with karma: 166 on 2019-02-19

Post score: 0

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

If getMessageValue or readBuffer have a never ending loop, the program will never pass the call to .join(), because there it waits for the threads to finish. If this is the case, the easiest solution might be to call .detach() instead of .join().

However, if the two thread functions are just message callbacks, you should indeed use the AsyncSpinner.

specifically how to assign a method to a thread spun by it

You do not have to manually assign a method here, this is done by registering the callbacks when subscribing to a topic. The AsyncSpinner then lets the number of threads you specified execute those callbacks. Surely you already saw the Wiki entry on callbacks, but it really explains how to do it.


Originally posted by cellard0or with karma: 61 on 2019-02-26

This answer was ACCEPTED on the original site

Post score: 0

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.