Multithreading counters with C + + 11 features

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.