Many parallel computing programs need to determine the number of data to be computed, or, in other words, to be coupled by number between multiple threads. At this point, by leveraging the atomic_ provided by C + + 11? Type, which enables multi-threaded security counters, thereby reducing the coupling between multiple threads to facilitate the writing of multithreaded programs.
Taking the counter implementation as an example, this paper demonstrates the implementation technique of multithreading counter, the code is as follows:
Objective: To test the use of C + + 11 features to implement the Counter method//Operating system: Ubuntu 14.04//publish_date:2015-1-31//Note the compile command used: g++-wl,--no-as-needed-std=c++0x Counter.cpp-lpthread#include <iostream> #include <atomic> #include <thread> #include <vector> Using namespace Std;atomic_int Counter (0); int order[400];void work (int id) {int no;for (int i = 0; i <; i++) {no = Co UNTER++;ORDER[NO] = ID;}} int main (int argc, char* argv[]) { vector<thread> threads;//Create multithreaded Access counter for (int i = 0; I! = 4; ++i) //Line process function and thread tag parameter threads.push_back (thread (work, i)); For (Auto & th:threads) th.join (); Final count value cout << "final:" << Counter << Endl; Observe the working sequence for each thread for (int i = 0; i < i++) cout << "[" << I << "]=" << Order[i] << ""; return 0;}
Note the parameters of the compile command, in particular, the-lpthread
Otherwise, if there is no link parameter, the compilation will not be faulted, but a run-time error will occur:
Terminate called after throwing an instance of ' Std::system_error '
What (): Enable multithreading to use std::thread:operation not permitted
Abandoned (core dumped)
Multithreading counters with C + + 11 features