Multithreading in C++ … where to start?

我的梦境 提交于 2019-11-30 11:35:10

If you do not have a compiler that supports C++0x yet (available with visual studio c++ 2010 for example), use boost threads. (Unless you use a framework that already supports threading, which is not the case - you wouldn't ask the question otherwise -). These boost threads became actually the standard in the brand new C++. Before that time C++ itself was thread unaware.

TBB Threading Building Blocks might also be interesting to you if you want to learn other aspects in parallel programming.

Regarding Qt: if you only want threading support it is complete overkill. It has horribly slow round trip times from compiling to result. It is really well designed thought. But not an official standard like the C++0x threads from boost. Therefore I would not take it as a first choice.

In C++, yes threading is platform specific. However, many threading libraries encapsulate the nuances of threading on various platforms, providing a uniform API with which to write your threaded app, so you don't have to worry about platform specific details.

Boost threading library is a very good solution.

I also recommending checking out ACE as well.

Let's start backward:

How is it possible to implement threading in a library ?

It isn't, at least not in (pure) C++. This requires language support (the compiler is only an implementation).

At the moment 2 things are used:

  • assembly code for some parts (like in the pthread library)
  • specific compiler instructions for others (dependent on the compiler and platform)

Both are brittle and require a tremendous amount of work for portability. Basically it means lot of #ifdef portions in the code to test for the compiler and targetted architecture, test for the support of some directives etc...

That is why it was deemed necessary to add threading support in C++0x.

How do I do multithreading ?

Even before you choose a library, you should choose a method. There are 2 ways of programming multithreaded applications (and you can combine them):

  • Communicate by sharing: this means using mutexes, atomic operations, etc... you can use pthread on Linux platforms, but I would recommend Boost.Thread (among others) for its portability.
  • Share by communicating: more recent, and adapted to distributed computations, this stems from the functional languages. This means passing messages from one thread to another and not sharing any resources. You can use FastFlow or Intel's Thread Building Blocks aka TBB.

You can conceivably merge the two, but it would be better not to. Personally I have found the description of FastFlow totally awesome: it encourages lock-free programming. Also, the main advantage of the second method is that it's better adapted to multi-processes programming and scales to distributed environments.

To begin with, I would recommend focusing on either one and build some applications with it. When you're comfortable you may try out the other, but be ready to start anew, they are that different.

//This program explains how pthread works, here 5 thread are trying to update a global variable simultaneously but with locking synchronization in maintained
#include<iostream>
#include<pthread.h>
using namespace std ;

#define MAX_NO_THREAD 5

    int global_sum = 0 ;
    pthread_mutex_t lock ;    //Declared global lock mutex object

void *print_fun(void *arg)
{
    cout<<"\nThread id : "<<(int)arg;
    pthread_mutex_lock(&lock) ; //aquiring lock on piece of code
    for ( int j=0; j<100000000; j++)
    {
        global_sum++ ;
    }
    pthread_mutex_unlock(&lock) ; //reomving lock on peice of code
    cout<<"\nGlobal Sum : "<<global_sum ;
}

int main()
{
    int i = 0 ;
    pthread_t threads_obj[MAX_NO_THREAD] ; //Initializing object array for thread
    pthread_mutex_init(&lock, NULL) ; //Initalinzing lock object for thread
    int st ;
    for ( i=0; i<5; i++)
    {
        pthread_create(&threads_obj[i], NULL, *print_fun, (void *)i) ;//Initializing threads calling function print_fun
        pthread_join(threads_obj[i], 0) ; //Forcing main thread to main until these thread complete
    }
    pthread_mutex_destroy(&lock) ; //Destroying lock object
}



//compile this program using -lpthread option with g++
//g++ thread.cc -lpthread

also check out Qt

To offer a suggestion different from Boost, I use Pthreads (or Pthreads-Win32 on Windows). It's a very do-it-yourself barebones library, but provides you with all you need and nothing else. It's very lightweight compared to Boost and you can easily find C++ wrappers around it to give you higher level abstractions.

you might also consider openmp http://openmp.org. Many compilers support it, including MS, GCC/G++ and Intel. Although you don't get explicit control of threads, its higher level abstraction of parallelism is sometimes more efficient (at coding time as well as runtime), and the code is much easier to understand. It's not going to help you much if you're doing GUI work, but for scalable computation it's worth a look.

The Boost Threading Library is probably the best place to start for C++. Gives you threading contructs, as well as all the mutexes and control objects you need to write a real working multithreaded application.

With C++11, "Thread support library" is introduced under <thread> header.

More info could be found from below links

https://en.cppreference.com/w/cpp/thread

http://www.cplusplus.com/reference/thread/

If you're doing this out of interest to improve your knowledge of different programming models and language skills then the Boost library would be a fine way to go. However I would think long and hard about actually building any production applications using multi-threaded C++.

C++ is challenging enough at times to attain correctness without adding the considerable complexity of shared memory multi-threading. Even the most seasoned programmers would agree that multi-threaded programs are extremely hard to reason about and get right. Even the simplest programs can quickly become hard to test and debug when multi-threaded.

Imperative languages such as C++ or Java or C# (with their mutable variables, shared memory and locking/signalling primitives) are very often the least approachable way to try to build multi-threaded applications. There are usually perfectly good single threaded implementation options to accomplish most user-space (as opposed to kernel or embedded) application problems, including on multi-core machines.

If you really want to build reliable "multi-threaded" applications I would suggest you check out functional languages like Erlang, Haskell, F# or Clojure.

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