3

我这里有这个用 g++ theFile.cc -lboost_thread 编译的测试用例。运行程序时,它似乎挂在 join 命令上。我不确定为什么。就像 interrupt_point() 函数没有从主线程获取加入请求一样。

#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;
}

谢谢阅读。

编辑:另外,如果你删除 while 循环,程序会干净地退出......提升版本 1.39.0

4

2 回答 2

2

看来您的停止功能实际上并没有中断线程。调用 join 并不意味着中断,相反,如果您希望中断而不是等待正常终止,则必须在加入之前通过调用 .interrupt() 显式执行此操作。

于 2009-12-25T04:15:40.703 回答
1

线程可以捕获中断异常并无限期地继续处理。为了使中断成为最终的,异常必须未被捕获,或者您可以捕获并停止处理,或者您可以使用更具破坏性的东西,例如 TerminateThread 或 pthread_cancel,它们可能并不总是完成所有清理工作。

请注意,线程可以使用 boost::this_thread::disable_interruption 禁用中断。

于 2009-12-25T03:46:04.960 回答