Thread in C++ in MacOS X

删除回忆录丶 提交于 2019-12-07 00:28:20

问题


I'm trying to run some code using threads in standard C++ (installed with XCode) in MacOS X Mavericks. But I'm getting some errors. Here's a minimal working example:

#include <thread>
#include <iostream>

void run (int x) {
    std::cout<<".";
}

int main (int argc, char const *argv[])
{
    std::thread t(run);
}

The error I'm getting:

minimal.cpp:10:17: error: no matching constructor for initialization of 'std::thread'
std::thread t(run,0);
            ^ ~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/thread:372:9: note: candidate constructor template not viable: requires single argument '__f', but 2 arguments
  were provided
thread::thread(_Fp __f)
    ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/thread:261:5: note: candidate constructor not viable: requires 1 argument, but 2 were provided
thread(const thread&);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/thread:268:5: note: candidate constructor not viable: requires 0 arguments, but 2 were provided
thread() _NOEXCEPT : __t_(0) {}
^
1 error generated.

I've been able to track the problem to my compiler defining _LIBCPP_HAS_NO_VARIADICS, which is defined because of

#if !(__has_feature(cxx_variadic_templates))
#define _LIBCPP_HAS_NO_VARIADICS
#endif

Any help would be appreciated.

Thank you!


回答1:


Thanks to pwny and PeterT, I figured out the error.

I just needed to compile with clang++ -std=c++11 minimal.cpp and it worked like a charm. I also needed a t.join() at the end to prevent an execution error to happen.




回答2:


i'm getting different std::thread behaviour running same app. on xcode or instruments (profiling), on xcode the single thread/multithread ratio is 0.6 and in instruments is 3.7 using a 4 thread array,

how is this possible?

 Xcode run:

st...ok - lap: 4875 ms
st/8...ok - lap: 1205 ms
mt...ok - lap: 8330 ms
st/mt ratio:**0.6**

Instruments run:

st...ok - lap: 2182 ms
st/8...ok - lap: 545 ms
mt...ok - lap: 596 ms
st/mt ratio:**3.7**


来源:https://stackoverflow.com/questions/22031640/thread-in-c-in-macos-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!