我正在编写一个简单的C++程序来演示锁的使用.我正在使用codeblocks和gnu gcc编译器.
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
int x = 0; // shared variable
void synchronized_procedure()
{
static std::mutex m;
m.lock();
x = x + 1;
if (x < 5)
{
cout<<"hello";
}
m.unlock();
}
int main()
{
synchronized_procedure();
x=x+2;
cout<<"x is"<<x;
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:mutex in namespace std does not name a type.
为什么我收到此错误?编译器是否支持使用锁?
我一直在尝试让C++ 11工作,在浏览了不同的网站和Q/A之后,我仍然遇到了麻烦.我想和libstdc ++一起使用clang.它在clang状态中表示它受补丁支持 - http://clang.llvm.org/libstdc++4.7-clang11.patch.我从macports下载gcc4.7并在gcc4.7的头文件中做了相应的更改
我不使用libc ++的原因是因为libc ++和libstdc ++之间的ABI兼容性,由这个线程表示:为什么不能用c ++ 0x模式中的libc ++来链接这个boost :: program_options示例?
好的,一切都完成后,我使用以下代码测试了我的设置:
#include <mutex>
#include <thread>
int main ( ) {
std::mutex myMutext;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我期待include应该在c ++ 11下工作.
所以这就是我用GCC编译它的方法
g++ -std=c++11 -I/opt/local/include/gcc47/c++ -L/opt/local/lib/gcc47 main.cpp -o main
Run Code Online (Sandbox Code Playgroud)
编译成功
与Clang
clang++ -std=c++11 -I/opt/local/include/gcc47/c++ -L/opt/local/lib/gcc47 main.cpp -o main
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
@work:boostTest$ clang++ -std=c++11 -I/opt/local/include/gcc47/c++ -L/opt/local/lib/gcc47 main.cpp -o main
In file included from main.cpp:1:
In file included from /opt/local/include/gcc47/c++/mutex:38:
In file included from /opt/local/include/gcc47/c++/tuple:37:
In file included from /opt/local/include/gcc47/c++/utility:70: …Run Code Online (Sandbox Code Playgroud)