Transferred from: http://www.cnblogs.com/lidabo/p/3908705.html
This tutorial code is available on GitHub: Https://github.com/sol-prog/threads.
In previous teaching, I showed some of the most recent c++11 language content:
- 1. Regular Expressions (http://solarianprogrammer.com/2011/10/12/cpp-11-regex-tutorial/)
- 2. Raw String (http://solarianprogrammer.com/2011/10/16/cpp-11-raw-strings-literals-tutorial/)
- 3. Lambda (http://solarianprogrammer.com/2011/11/01/cpp-11-lambda-tutorial/)
Perhaps supporting multithreading is one of the biggest changes in the C + + language. Previously, C + + could only take advantage of the operating system's functionality (Unix family systems using the Pthreads Library) or, for example, OpenMP and MPI, to achieve the goal of multi-core computing.
This tutorial is intended to give you a head start on the c++11 thread, rather than simply listing the language standards here.
Creating and starting a C + + thread is as simple as adding a thread header file to a C + + source. Let's take a look at how to create a simple HelloWorld with threading:
#include "iostream"
#include "Thread"
This function would be is called from a thread
The function will be called in a thread
void Call_from_thread () {
Std::cout << "Hello, World" << Std::endl;
}
int main () {
Launch a thread
Start a thread
Std::thread T1 (call_from_thread);
Join the thread with the main thread
Collaboration with the main thread
T1.join ();
return 0;
}
On Linux systems, the above code can be compiled with g++:
g++-std=c++0x-pthread File_name.cpp
On a xcode4.x system, you can compile the above code with clang++:
clang++-std=c++0x-stdlib=libc++ File_name.cpp
On the Windows system, you can use the paid code base, Just::thread, to compile multithreaded code. Unfortunately, they didn't provide a trial version of the code base, and I couldn't do the testing.
In real-world applications, the function "Call_from_thread" is relative to the main function, doing some arithmetic work independently. In the preceding code, the main function creates a thread and waits for the T1 thread to run at T1.join (). If you forget to consider waiting for a thread to end up in the code, the main thread might end its own running state, and the entire program will kill the previously created thread when it exits, regardless of whether the function "Call_from_thread" has finished executing.
The above code is relatively concise compared to the equivalent code using POSIX threads. Look at the equivalent code using POSIX threads:
This function would be is called from a thread
void *call_from_thread (void *) {
Std::cout << "launched by thread" << Std::endl;
return NULL;
}
int main () {
pthread_t T;
Launch a thread
Pthread_create (&t, NULL, call_from_thread, NULL);
Join the thread with the main thread
Pthread_join (t, NULL);
return 0;
}
We usually want to start multiple threads at once to work in parallel. To do this, we can create a thread group instead of creating a thread as in the previous example. In the following example, the main function creates 10 threads for a set, and waits for those threads to complete their task (also included in the GitHub code base is the POSIX version of this example):
...
static const int num_threads = 10;
...
int main () {
Std::thread T[num_threads];
Launch A group of threads start a set of threads
for (int i = 0; i < num_threads; ++i) {
T[i] = Std::thread (call_from_thread);
}
Std::cout << "launched from the Mainn";
Join the threads with the main thread
for (int i = 0; i < num_threads; ++i) {
T[i].join ();
}
return 0;
}
Remember, the main function is also a thread, often called the main thread, so the above code actually has 11 threads running. After these thread groups are started, the thread group and the main function are allowed to do some other things before they are co-ordinated (join), and at the end of the tutorial we will use an example of image processing to illustrate them.
What about using a function with formal parameters in a thread? C++11 allows us to call in the thread, with any required parameters. To illustrate, we can modify the above code to accept an integer parameter (the POSIX version of this example is also included in the GitHub code base):
static const int num_threads = 10;
This function would be is called from a thread
void call_from_thread (int tid) {
Std::cout << "launched by thread" << tid << Std::endl;
}
int main () {
Std::thread T[num_threads];
Launch a group of threads
for (int i = 0; i < num_threads; ++i) {
T[i] = Std::thread (Call_from_thread, i);
}
Std::cout << "launched from the Mainn";
Join the threads with the main thread
for (int i = 0; i < num_threads; ++i) {
T[i].join ();
}
return 0;
}
On my system, the result of the above code is:
sol$./a.out
Launched by thread 0
Launched by thread 1
Launched by thread 2
Launched from the main
Launched by thread 3
Launched by thread 5
Launched by thread 6
Launched by thread 7
Launched by thread launched by thread 4
8L
Aunched by Thread 9
sol$
Can see the above results, once the program creates a thread, its operation has a sequence of uncertain phenomenon. The programmer's task is to make sure that the set of threads does not block when accessing public data. In the last few lines, the displayed output of the disorder shows that when the Line 8 line is started, the Line 4-line process has not yet completed the write operation on the stdout. In fact, assuming that you run the above code on your own machine, you'll get a completely different result, or even some confusing character output. The reason is that the 11 threads within the program are competing to use the STDOUT public resource (case: Race Conditions).
To avoid the above problem, you can use interceptors (barriers) in your code, such as Std:mutex, to make a bunch of threads access the public resources in a synchronous (synchronize) manner, or, if feasible, to set aside private data structures for the threads and avoid using public resources. We will also talk about thread synchronization in future teaching, including the use of atomic manipulation types (atomic types) and mutexes (mutexes).
In principle, the concepts that are required to write more complex parallel code are discussed in the code above.
If you are interested in learning the new c++11 grammar, I recommend reading Professional C + +, or C + + Primer Plus. C++11 multithreaded theme, it is recommended to read "C + + Concurrency in action", which is a good book.
C++11 Multi-Threading teaching