injoy
injoy

Reputation: 4373

error: expected unqualified-id while using boost mutex

I try to implement a lock macro based on boost mutex, the code is below:

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

using namespace std;

#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));
}

void thread()
{
    Mutex mtx;
    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();
}

When I compile it in the Mac OS using clang++ -std=c++11 -stdlib=libc++ lock_raii.cc -lboost_system -lboost_thread. There's an error message:

lock_raii.cc:16:10: error: expected unqualified-id
                mutex_.lock();
                       ^
lock_raii.cc:6:17: note: expanded from macro 'lock'
#define lock(x) if(Lock _lock_=x){}else
                ^
1 error generated.

So, what's the problem with it?

Upvotes: 0

Views: 582

Answers (1)

Jesse Good
Jesse Good

Reputation: 52365

Here is what mutex_.lock(); looks like after macro expansion:

mutex_.if(Lock _lock_=){}else;

Upvotes: 1

Related Questions