C++ threading in linux

I'm trying to create a multi-threaded c++ program in Linux. I've used the pthreads library before on windows, but I've heard it's not standard with Linux. What threading library would you advise for c++ with Linux? What options are there, what's the most common, and what's usually the fastest? Thanks!

edit: I was mistaken about pthreads not being native to linux, as I said, it was something I heard awhile ago. I was mainly looking for a comparison between the efficiencies of the various threading options, and was especially curious about info on how the c-11 threading library performed vs the pthreads I've used before. I was misinformed, and I posted this question to get more informed. There's no need to be nasty.


If you're using C++11, just use std::thread . It's fairly simple to do so. For example:

#include <thread>

void thread_entry(int foo, int bar)
{
    int result = foo + bar;
    // Do something with that, I guess
}


// Elsewhere in some part of the galaxy
std::thread thread(thread_entry, 5, 10);
// And probably
thread.detach();

// Or
std::thread(thread_entry).detach();

It's simple and should be sufficient for most purposes (though depending on the implementation, it might depend on pthreads).

If not, just use pthreads, since you're familiar with it. It's part of the POSIX standard, which most Linux distributions are mostly compliant with — at least, they're compliant enough that any differences won't matter to you.


Assuming you are not doing anything specifically "windowsy", your windows code using pthreads should work just the same on Linux or any other form of Unix (as long as it's reasonably modern - as in from the last 10 years or so since pthreads were introduced).

You could also, of course use the std::thread , since that is supported by C++11, and unless you have a really old version of g++, it should provide what you need, with an object oriented interface - and again, this should work on Windows and Linux equally (subject to having a modern enough compiler and standard library, of course).

链接地址: http://www.djcxy.com/p/40336.html

上一篇: gprof是否支持多线程应用程序?

下一篇: Linux中的C ++线程