LoginSignup
0
0

More than 1 year has passed since last update.

ros c++ boost::threadを使う

Last updated at Posted at 2022-01-17

はじめに

rosをインストールするときインストールされるboostを使用してthreadを行う方法

環境

ros-noetic

内容

1.パッケージを作成
2.プログラム作成

src/thread_sample.cpp
#include <iostream>
#include <boost/thread.hpp>

#define LOOP_NUM 5

// hogehogeと標準出力する関数
void Hoge() {
  for(int i = 0; i != LOOP_NUM; i++) {
    // hogehogeと標準出力(標準出力はスレッドセーフじゃないから本当は排他制御が必要だけど今回は省略)
    std::cout << "hogehoge" << std::endl;

    // 100ミリ秒スリープ
    boost::this_thread::sleep(boost::posix_time::milliseconds(100));
  }
}

// piyopiyoと標準出力する関数
void Piyo() {
  for(int i = 0; i != LOOP_NUM; i++) {
    // piyopiyoと標準出力(標準出力はスレッドセーフじゃないから本当は排他制御が必要だけど今回は省略)
    std::cout << "piyopiyo" << std::endl;

    // 100ミリ秒スリープ
    boost::this_thread::sleep(boost::posix_time::milliseconds(100));
  }
}

// main
int main() {
  // Hogeスレッドの生成と実行(&は無くてもよい)
  boost::thread th_hoge(&Hoge);

  // Piyoスレッドの生成と実行(&は無くてもよい)
  boost::thread th_piyo(&Piyo);

  // スレッドの終了を待つ(逆順でも問題ない)
  th_hoge.join();
  th_piyo.join();

  return 0;
}

引用: https://www.mathkuro.com/c-cpp/boost/how-to-use-boost-thread/

3.CMakeLists.txtを以下のように変更

CMakeLists.txt
cmake_minimum_required(VERSION 3.0.2)
project(boost_sample)

find_package(catkin REQUIRED)

## (ref) https://stackoverflow.com/questions/56575376/cmake-with-boost-thread-library
find_package(Boost REQUIRED COMPONENTS thread) ## add

catkin_package(
)

include_directories(
# include
# ${catkin_INCLUDE_DIRS}
  ${Boost_INCLUDE_DIRS} ## add 
)

message(${Boost_VERSION_STRING}) ## add

add_executable(thread_sample src/thread_sample.cpp)
target_link_libraries(thread_sample
  Boost::thread ## add 
)

以上

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0