Skip to content

Boost:Thread

Portable C++ multi-threading.

How to use

Boost.Thread를 사용하기 위하여 아래와 같이 설정해야 한다.

  1. BOOST_THREAD_USE_LIB를 define한다.
  2. libboost_thread.a를 링크한다.
  3. 경우에 따라서 libboost_system.a를 링크한다.

Example

#include <iostream>
#include <boost/thread.hpp>
using namespace std;

class CSampleIO
{
public:
    void TestThread()
    {
        while (1) {
            cout << "1 ";
            boost::this_thread::sleep(boost::posix_time::millisec(500));
        }
    }

    void TestThreadSecond(int num)
    {
        while (1) {
            cout<<num<<" ";
            boost::this_thread::sleep(boost::posix_time::millisec(500));
        }
    }

    void TestThreadThird(int num, int num2)
    {
        while (1) {
            cout<<num<<" ";
            boost::this_thread::sleep(boost::posix_time::millisec(500));
        }
    }
};

int main()
{
    CSampleIO io;

    // 스레드생성 (인자는 계속 추가 시킬 수 있음).
    boost::thread th1 = boost::thread( boost::bind(&CSampleIO::TestThread, &io)  );
    boost::thread th2 = boost::thread( boost::bind(&CSampleIO::TestThreadSecond, &io, 2)  );
    boost::thread th3 = boost::thread( boost::bind(&CSampleIO::TestThreadThird, &io, 3, NULL)  );

    // join에서 해당 스레드가 시작 됨.
    th1.join();
    th2.join();

    return 0;
}

Boost::Thread의 자세한 설명은 std::thread로 대체 참조하기 바란다.

Troubleshooting

undefined reference to boost::detail::set_tss_data

아래와 같은 에러가 발생할 수 있다.

./libworld-g.a(Log.world-g.o): In function `ZN5boost19thread_specific_ptrINS_3log9v2_mt_nt55sinks30basic_formatting_sink_frontendIcE18formatting_contextEED1Ev':
C:/workspace/root/var/opm/local/include/boost/thread/tss.hpp:79: undefined reference to `boost::detail::set_tss_data(void const*, boost::shared_ptr<boost::detail::tss_cleanup_function>, void*, bool)'
./libworld-g.a(Log.world-g.o): In function `ZNK5boost19thread_specific_ptrINS_3log9v2_mt_nt55sinks30basic_formatting_sink_frontendIcE18formatting_contextEE3getEv':
C:/workspace/root/var/opm/local/include/boost/thread/tss.hpp:84: undefined reference to `boost::detail::get_tss_data(void const*)'
./libworld-g.a(Log.world-g.o): In function `ZN5boost19thread_specific_ptrINS_3log9v2_mt_nt55sinks30basic_formatting_sink_frontendIcE18formatting_contextEE5resetEPS6_':
C:/workspace/root/var/opm/local/include/boost/thread/tss.hpp:105: undefined reference to `boost::detail::set_tss_data(void const*, boost::shared_ptr<boost::detail::tss_cleanup_function>, void*, bool)'

이 경우 libboost_thread를 링크하기 바란다. C++11의 std::thread를 사용하더라도 Boost:Log등을 사용할 경우 링커에 추가해야 한다.

See also

Favorite site

References


  1. Unavailable_the_boost_threads_library.pdf