0

我尝试实现一个基于boost互斥锁的锁宏,代码如下:

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

当我在 Mac OS 中使用clang++ -std=c++11 -stdlib=libc++ lock_raii.cc -lboost_system -lboost_thread. 有一条错误消息:

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.

那么,它有什么问题呢?

4

1 回答 1

2

这是mutex_.lock();宏扩展后的样子:

mutex_.if(Lock _lock_=){}else;
于 2013-10-09T20:36:52.133 回答