c++ -std=c++11 -Wall -g threads.cpp -o threads.out
In file included from threads.cpp:1:
In file included from /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/iostream:37:
In file included from /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/ios:215:
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/__locale:401:32: error: use of undeclared identifier '_ISspace'
static const mask space = _ISspace;
^
Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/__locale:402:32: error: use of undeclared identifier '_ISprint'
static const mask print = _ISprint;
^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/__locale:403:32: error: use of undeclared identifier '_IScntrl'
static const mask cntrl = _IScntrl;
^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/__locale:404:32: error: use of undeclared identifier '_ISupper'
static const mask upper = _ISupper;
^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/__locale:405:32: error: use of undeclared identifier '_ISlower'
static const mask lower = _ISlower;
^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/__locale:406:32: error: use of undeclared identifier '_ISalpha'
static const mask alpha = _ISalpha;
你能帮我解决这个__locale问题,同时编译c++代码。
#include <iostream>
#include <thread>
using namespace std;
void fun(void)
{
cout << "Vaule " << 10 << endl;
}
int main()
{
thread t1(fun);
thread t2(fun);
return 0;
}
编译命令:c++ -std=c++11 -Wall -g thread.cpp -o thread.out
有两件事可以解决这个问题。
首先,添加编译器选项-pthread
。我的编译命令:clang++ -Wall -Wextra -std=c++11 -pthread main.cpp
处理第二件事,在结束程序之前连接你的线程。
t1.join();
t2.join();
它不修复的东西,是你的std::cout
语句很可能是混乱的,因为线程只是把他们的数据转储到单个流,因为他们喜欢。例如,我的输出如下:
Vaule Vaule 10
10
为了解决这个问题,您可能需要在std::cout
语句周围放置一个锁(互斥锁)。
正如我在我的评论中所说,我不建议使用g++
,除非你自己安装它。您正在使用的命令是一个不正常的别名,因为您遗漏了一些文本。
❯ g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.0 (clang-1200.0.32.29)
Target: x86_64-apple-darwin20.3.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
与clang++对比
❯ clang++ --version
Apple clang version 12.0.0 (clang-1200.0.32.29)
Target: x86_64-apple-darwin20.3.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
在g++部分中值得注意的是'Configured with'行。它使用来自gcc 4.2.1的标准库,它是c++ 11之前的版本。你不应该把那个信息遗漏。