Ask Your Question
0

Stopping std::threads in ROS [closed]

asked 2019-02-19 02:23:10 -0500

curi_ROS gravatar image

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;
}
edit retag flag offensive reopen merge delete

Closed for the following reason the question is answered, right answer was accepted by curi_ROS
close date 2019-05-15 05:58:35.372763

1 Answer

Sort by ยป oldest newest most voted
0

answered 2019-02-26 05:22:02 -0500

cellard0or gravatar image

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.

edit flag offensive delete link more

Question Tools

2 followers

Stats

Asked: 2019-02-19 02:23:10 -0500

Seen: 290 times

Last updated: Feb 26 '19