开发者

boost thread and join

I've got this test case here that compiles with g++ theFile.cc -lboost_thread. When running the program it seems to be hanging at the join command. I'm not exactly sure why. It's like the interrupt_point() function isn't getting the join request from the main thread.

#include <iostream>
#include <stdio.h>
#include <signal.h>
#include <fstream>
#include <boost/thread.hpp>

using namespace std;


//////////////////////////////////

  class SerialnIMU {
  public:
    ~SerialnIMU();

    void start();
    void stop();
  private:
    boost::thread readThread;

    class SerialReader {
    public:

      void operator()();
    private:
    };
  };

////////////////////////////////


SerialnIMU::~SerialnIMU() {
  stop();
}

void SerialnIMU::start() {
  readThread = boost::thread(SerialReader());
  cout<<"Created: "<<readThread.get_id()<<endl;
}

void SerialnIMU::stop() {
  cout<<"Join: "<<readThread.get_id()<<endl;
  cout<<"Joining serial thread..."<<endl;
  readThread.join();
  cout<<"Done."<<endl;
}

//////////////////////serial thread//////////////////

void SerialnIMU::SerialReader::operator()() {
  cout<<"Serial reading thread started..."<<endl;
  try {
    while(true) {
      boost::this_thread::interruption_point();
    }
  } catch(...) {
开发者_运维知识库    cout<<"exception was thrown."<<endl;
  }
  cout<<"Serial reading thread stopped."<<endl;
}


int main(int argc, char **argv) {

  SerialnIMU imu;

  imu.start();
  imu.stop();
  return 0;
}

thanks for reading.

EDIT: also, if you remove the while loop the program exits cleanly... boost version 1.39.0


It appears that your stop function doesn't in fact interrupt the thread. Calling join does not imply interruption, instead you have to do it explicitly by calling .interrupt() before joining if you wish to interrupt rather than wait for normal termination.


A thread can catch the interruption exception and keep processing indefinitely. For the interruption to be final, the exception must go uncaught, or you can catch and stop processing, or you can use something a bit more destructive like TerminateThread or pthread_cancel which may not always do all the cleanup.

Note it's possible for a thread to disable interruptions with boost::this_thread::disable_interruption.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜