views:

755

answers:

15

What is the easiest way to create multithreaded applications with C/C++?

+5  A: 

pthreads!

https://computing.llnl.gov/tutorials/pthreads/

Carl Norum
This is something I would consider unhelpful, especially versus the recommendation of boost. Posix isn't easily portable to Win32 environments, and the API is about primitive as you can get.
Jherico
Well it clearly isn't going to make multithreading programming easy, but at least it's well documented.
Carl Norum
pthreads are supported on windows: http://sourceware.org/pthreads-win32/ All threading APIs are primitive... If you want higher level than you can use a threadpool, or actors, or some other abstraction over threads.
Greg Rogers
pthreads works fine on windows. Is not the windows API just a layer over pthreads.
Martin York
@Greg: Not all threading APIs are *stoneage* primitive though. Boost manages to implement a threading API which preserves type safety and actually behaves well in a C++ application. pthread does nothing to make it easier to use, or to prevent programmer errors.
jalf
pthreads probably doesn't qualify as "easiest", since there are other threading libraries that are dirt-simple to use. But I don't think it's a bad answer, since pthreads is the "source of power" on POSIX platforms.
Tom
+13  A: 

There is no easy way to create a multithreaded application in any language.

voyager
This is not true. Choosing the right language for the task can make multithreaded programming easy.
Amuck
i asked about the easiest way
SomeUser
Multithreaded programming can **look** easy given a simple language, but its one of the most difficult programming problems to get right. *If you think you are smart enough to implement correct multithreading, you are most liekly not*
voyager
Amuck: Multithreaded programming is never easy. Regardless of the level of support, thrashing, spinning, deadlocking, and all the other pitfalls of multithreaded programming will not be easy to overcome.
jmucchiello
@AndrewSmith: this is a half joke, half infomative answer :)
voyager
Sure is. If the program is sufficiently trivial. ;)Starting two threads which never ever share data is pretty easy.
jalf
You should deffinetly read http://www.randomtree.org/eric/techblog/2004/10/multithreading-is-hard.html http://www.virtualdub.org/blog/pivot/entry.php?id=62
voyager
@jalf: getting those two threads to do something useful, on the other hand... ;)
voyager
This is not an answer.
Jodi
Even if every method of writing multithreaded apps is hard, by definition at least one of them must be easiest. :p
Philip Davis
You are basically saying that all ways to create a multithreaded application are equally difficult. That's not true. Btw, this site is about getting anwers, not getting preached at.
StackedCrooked
@voyager "Let's go shopping."
Pete Kirkham
@voyager: That is why you pick a language were the engineer is removed from the problem and pick a language where the compiler does it for you. SISAL and OCCAM spring to mind but I am sure there are others.
Martin York
Always worth citing at a time like this -- Boehm, Threads Cannot be Implemented as a Library http://www.hpl.hp.com/techreports/2004/HPL-2004-209.html
Steve Gilham
@StackedCrooked: I didn't want to preach, just don't want to give the deceptive idea that multithreading *is* easy. Why do you think I CWed the answer? I know there are answers to this question, this is more of a side note, a glorified comment if you want.@Martin York: of course, but the current tools for multithreading don't make it as easy as it could be.@Pete Kirkham: I don't say "don't multithread", I say "multithread carefully". Be aware that most likely than not there will be bizzare bugs and issues due to multithreading.
voyager
+13  A: 

unfortunately there is no easy way. Couple of options: pthread on linux, win32 api threads on windows or boost::thread library

vehomzzz
+1  A: 

I would say with Qt. Qt Threads and Qt Concurrency are probably worth googling.

+7  A: 

Qt has a pretty threading support and documentation but as others have cautioned this is not for beginners. The doc link I gave itself points to a short reading list

Dirk Eddelbuettel
+2  A: 

The C++0x specification includes threading facilities (one of my favorite new features). Soon it won't matter what OS you're compiling for! Just look how easy it is to create a new thread and join back to the creator thread:

#include <thread>
#include <iostream>

class SayHello
{
public:
    void operator()() const
    {
        std::cout<<"hello"<<std::endl;
    }
};

int main()
{
    std::thread t((SayHello()));
    t.join();
}

Visual Studio 2010 is implementing parts of C++0x but we're still waiting on the threading facilities.

James Jones
As long as you're willing to put up with C++, anyway. You could do it right now in Java, if you want to make that case.
Carl Norum
Dude.. The question specifies C/C++.
James Jones
@James, unless things have changed recently I don't think std::thread won't be complete alternative for existing implementations like POSIX threads. In particular it is missing features like thread priorities. See this SO answer for details: http://stackoverflow.com/questions/1273572/will-pthreads-become-obsolete-once-stdthread-makes-into-cox/1274301#1274301 ... Regardless, there is no denying std::thread will be a very welcome addition to the standard.
Void
+3  A: 

It's been a while since I worked in C++ and I haven't seen the Boost threading support, but I found it very helpful to encapsulate semaphore services provided by the OS, usually either POSIX or Win32, in simple classes that would acquire locks, and release them in the destructors, making their use fairly simple.

void operateOnSharedResource(SharableResource & foo) {
    MutexLock lock(foo.getMutex());
    // do stuff to foo
    // implicit call to MutexLock dtor performs release 
}

Ultimately there are lots of simple tricks like this to ease thread programming and I'd be surprised if Boost didn't have something like this by now (EDIT: It does and it's documented in Lock Types).

Regardless, the main problem with writing multi-threaded code isn't going to be solved by any third party library, and that's understanding where your code can be parallelized usefully, and where shared resources are going to be touched and must be accounted for. Here's a few rules of thumb I use when writing multi-threaded code.

  • Try to minimize the number of shared resources
  • Try to encapsulate shared resources in class wrappers that make all operations atomic.
  • Make worker threads as simple as possible

Proper encapsulation really does wonders for writing safer multi-threaded code, because the fewer things you can see, the fewer things can have a race condition.

Jherico
+5  A: 

There is no simple answer to this. It depends very heavily on what you hope to gain from multithreading, the platform/compiler, and which threading model you want to use. Every threading API has its pitfalls.

And just because no one has mentioned it so far, OpenMP is another option that is supported in many modern mainstream compilers and is intended to simplify the use of concurrency. http://openmp.org/wp/

Alan
+7  A: 

Just to mention it because it hasn't been mentioned: a compiler with OpenMP support (http://openmp.org/wp/)

Tobias Langner
I totally agree!
Jacob
If you can fit your program into this model then this definitely is the easiest way. In fact I'm in the process of writing a short test program using OpenMP for just this reason.
Max Lybbert
+2  A: 

I'm not sure about the easiest, but IMO the most user-friendly threading library is the one included in the Poco C++ project. For a preview have a look at the Thread.h header file.

StackedCrooked
+1  A: 

Posix Thread is quite good, they also come with great documentation and tutorials.

Not as easy as java threads, but still quite good.

Kazoom
+1  A: 

This depends entirely on what you're doing. If you can fit what you're doing into OpenMP then that is the way to go. Otherwise you may want to look at Intel's TBB. TBB offers several workflows which you should be able to fit into, but the library is dual licensed and you may not be able to accept either license. If both OpenMP and TBB are out, then you should consider your operating system's thread pools abilities.

At some point you may need to bite the bullet and use Boost.Thread. If so, you'll want to look at what makes multithreading in C++ hard (good to read even if you're not using C++0x: "It's not the threads themselves, it's the communication that causes problems. Mutable shared state introduces implicit communication," page 3).

Max Lybbert
+2  A: 

Boost.Thread is relatively easier because it's portable, well-documented and has high-level API such as scoped_try_lock.

torus
+1  A: 

The easiest way is by avoiding/minimizing mutable shared state.

Once you have mutable shared state, you need to deal with locking which is where the bulk of the difficulty in writing multi-threaded programs exists.

R Samuel Klatchko
+2  A: 

Besides the ones already mentioned, ACE is another popular and widely deployed C++ framework that provides thread encapsulations across multiple platforms. It's style of C++ isn't as modern as Boost.Thread, for example, but it is quite mature.

Void