剥离.gnu.version节时出现段错误

时间:2019-02-27 15:30:08

标签: c++11 segmentation-fault pthreads strip chrono

我正在使用线程库和计时库基于C ++ 11的旧框架重写旧代码。 总而言之,该库会产生一个线程并等待事件或延迟。

我的问题是,当我剥离二进制文件删除.gnu.version部分时,程序出现段错误。
我想知道本节的目的是什么,将其从二进制文件中剥离会如何导致不同的行为并导致段错误?


我编写了一个代码示例,该示例在删除.gnu.version部分之前一直有效。

1。编译

  

g ++ -std = c ++ 11 test.cpp -o test -pthread -lpthread

2。删除前执行

$ ./test
>>run()
  run() - before wait()
>>wait()
< wait()
  run() - after wait()
  run() - before wait_until()
  run() - after wait_until()
  run() - before wait()
  run() - after wait()
< run()

3。删除.gnu.version部分

  

strip -R .gnu.version测试

4。剥离后执行

 ./test
>>run()
  run() - before wait()
>>wait()
< wait()
  run() - after wait()
  run() - before wait_until()
Segmentation fault (core dumped)

根据我的调查,调用无延迟pthread库时,段错误发生在std::condition_variable::.wait_until()中。

这是代码示例:

#include <thread>
#include <iostream>
#include <condition_variable>
#include <unistd.h>

class Task
{
private:
    std::mutex _mutex;
    std::condition_variable _cv;
    std::thread _thread;
    bool _bStop;
    bool _bWait;

    void run()
    {
        std::unique_lock<std::mutex> lock(_mutex);
        std::cout << ">>run()" << std::endl;
        while (!_bStop)
        {
            if ( !_bWait )
            {
                std::cout << "  run() - before wait()" << std::endl;
                _cv.wait(lock);
                std::cout << "  run() - after wait()" << std::endl;
            }
            else
            {
                _bWait = false;
                std::chrono::steady_clock::time_point ts = std::chrono::steady_clock::now()
                                                         + std::chrono::seconds(1);
                std::cout << "  run() - before wait_until()" << std::endl;
                _cv.wait_until(lock,ts);
                std::cout << "  run() - after wait_until()" << std::endl;
            }
        }
        std::cout << "< run()" << std::endl;
    }

public:
    Task():_bStop(false),_bWait(false)
    {
    }

    void start()
    {
        _thread = std::thread(&Task::run,this);
    }

    void wait()
    {
        std::cout << ">>wait()" << std::endl;
        std::unique_lock<std::mutex> lock(_mutex);
        _bWait = true;
        _cv.notify_one();
        std::cout << "< wait()" << std::endl;
    }

    void cancel()
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _bStop = true;
        _cv.notify_one();
    }

    void join()
    {
        _thread.join();
    }
};

int main()
{
    Task t;

    // Start Task thread
    t.start();

    // Sleeping here seems to help produce the error
    usleep(10000);
    t.wait();

    // Wait for Task to process delay
    sleep(5);

    // Stop Task and wait for thread termination
    t.cancel();
    t.join();

    return 0;
}

0 个答案:

没有答案