简体   繁体   中英

Segmentation fault: 11 while using boost mutex

I implemented a lock macro based on boost mutex, the code is below:

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

#define LOCK(x) if(Lock _lock_=x){}else

class Mutex{
public:
    friend class Lock;

private:
    boost::mutex mutex_;

    void Lock(){
        mutex_.lock();
    };

    void Unlock(){
        mutex_.unlock();
    };
};

class Lock{
public:
    Lock(Mutex& mutex):mutex_(mutex){mutex_.Lock();};
    ~Lock(){mutex_.Unlock();};

    operator bool() const {
        return false;
    }

private:
    Mutex& mutex_;
};

void wait(int seconds)
{
    boost::this_thread::sleep(boost::posix_time::seconds(seconds));
}

Mutex mtx;

void thread()
{
    for (int i = 0; i < 5; ++i)
    {
        LOCK(mtx){
            wait(1);
            std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl;
        }
    }
}

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

I compiled it in the Mac OS using clang++ -std=c++11 -stdlib=libc++ lock_raii.cc -lboost_system -lboost_thread . When I run it, there is a Segmentation fault: 11 .

What's the problem with it?

Aside of the fact that this method at least questionable, I do not see a problem with the code. gcc v4.7.0 on Linux does not have issues either (there is no segmentation fault). So you may not setup boost properly or have a bug somewhere. You should run your program under debugger and see where the problem occurs. In theory this code:

if(Lock _lock_=x){}else

could be compiled as:

if(Lock _lock_= Lock(x) ){}else

and invoking copy ctor and have double unlock on the mutex. To make sure this is not the issue make copy ctor for class Lock private.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM