Multithreading Programming in C++11

Home / Multithreading Programming in C++11

Multithreading Programming in C++11

November 24, 2015 | Article | 1 Comment

Before C++11, C++ doesn’t support multi-threading natively. A C++ program for threading must depend on others threading implementation. That is a source code for Windows threading is different with POSIX-Unix threading. But the newest standard has including multithreading support natively. Hurray!

Let’s begin by creating and launching a thread in C++11.

[sourcecode language="cpp"]
#include <iostream>
#include <thread>
using namespace std;

void thread_main() {            // Entry point for thread
cout<<"Hello world"<<endl;
}
int main() {
thread thr(thread_main);    // Create a thread
thr.join();                      // Join the thread with main thread
}
[/sourcecode]

On Linux we can compile it with g++

g++ -std=c++0x -pthread filename.cpp

Of course as a different thread, the thread_main() be run independent form the main thread. In above example, after create new thread, we join the new thread with main thread so the main function will wait for the thread to finish. Because it is running independently, we cannot guarantee if thread_main() would exit before main() if we did not join them.

Now let’s look equivalent code using POSIX threads:

#include <iostream>
#include <pthread.h>
using namespace std;

//This function will be called from a thread
void *thread_main(void *) {
   cout << "Launched by thread" << endl;
   return NULL;
}

int main() {
   pthread_t t;

   //Launch a thread
   pthread_create(&t, NULL, thread_main, NULL);

   //Join the thread with the main thread
   pthread_join(t, NULL);
   return 0;
}

We can also launch more than one thread at once to achieve parallelism we want. In order to do this we could create an array of threads. Using the same source code as previous, let’s modify some parts:

#include <iostream>
#include <thread>
using namespace std;

static const int nmThreads = 10;
void thread_main(int arg) {
   cout<<"Launch by thread "<<arg<<endl;
}

int main() {
   thread T[nmThreads];

   // launch a group of threads
   for(int i=0; i<nmThreads; i++) {
      T[i] = thread(thread_main,i);
   }
   cout<<"Launch from the main\n";

   // Join the threads with the main thread
   for(int i=0; i<nmThreads; i++) {
      T[i].join();
   }
   return 0;
}

So how many threads we have? Yes, 11 including main. The above code runs 11 threads on a single process.

That is, running a multithreading on C++11 is now easier. Let see what we could expect later.

, , ,

About Author

about author

xathrya

A man who is obsessed to low level technology.

1 Comment
  1. C++11 Concurrency: Part 1 - Introduction to Threading in Standard Library - Xathrya.ID

    […] see also: Multithreading Support in C++11 […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Social media & sharing icons powered by UltimatelySocial