链接器错误与简单的线程程序(来自boost_chrono的符号丢失)

时间:2018-03-15 07:36:01

标签: c++ multithreading boost mutex

我正在学习boost :: timed_mutex

无法编译以下代码:

#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <iostream>

void wait(int seconds)
{
  boost::this_thread::sleep_for(boost::chrono::seconds{seconds});
}

boost::timed_mutex mutex;

void thread1()
{
  using boost::this_thread::get_id;
  for (int i = 0; i < 5; ++i)
  {
    wait(1);
    boost::unique_lock<boost::timed_mutex> lock{mutex};
    std::cout << "Thread " << get_id() << ": " << i << std::endl;
    boost::timed_mutex *m = lock.release();
    m->unlock();
  }
}

void thread2()
{
  using boost::this_thread::get_id;
  for (int i = 0; i < 5; ++i)
  {
    wait(1);
    boost::unique_lock<boost::timed_mutex> lock{mutex,
      boost::try_to_lock};
    if (lock.owns_lock() || lock.try_lock_for(boost::chrono::seconds{1}))
    {
      std::cout << "Thread " << get_id() << ": " << i << std::endl;
    }
  }
}

int main()
{
  boost::thread t1{thread1};
  boost::thread t2{thread2};
  t1.join();
  t2.join();
}

我的编译命令是:

g ++ -std = c ++ 11 unique_lock.cpp -o unique_lock -g -lboost_system -lboost_thread-mt -pthread -lboost_timer

错误如下:

/bin/ld: /tmp/ccRVKHNh.o: undefined reference to symbol '_ZN5boost6chrono12system_clock3nowEv'
/usr/lib64/libboost_chrono.so.1.53.0: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status

怎么了?

1 个答案:

答案 0 :(得分:1)

显然缺少-lboost_chrono。

Demo