C++11 new features atomic and thread

Source: Internet
Author: User
Tags thread class

It was only today that C++11 supported atomic operations and also supported the thread class to create threads, which is really getting 6. Before doing the project, the creation thread is the POSIX standard pthread_create function, and the thread synchronization is generally used Pthread_mutex. Today get a new skill, you can use the thread class to create a thread, with the Atomic_flag implementation of spin lock for thread synchronization, do not say, and quickly take the small notebook to write down:

1#include <iostream>2#include <vector>3#include <thread>4#include <atomic>5 using namespacestd;6 Longn=0;7Std::atomic_flagLock=Atomic_flag_init;8 voidThreadfun (intn)//Thread entry function9 {Ten      for(intI=0; i<10000000; ++i) One     { A          while(Lock. Test_and_set ());//Spin lock -++N; -         Lock. Clear (); the     } - } - intMain () - { +Vector<thread>Threadarray; -     intthreadnum=2; +cout<<"I am Main thread, n="<<N<<Endl; A      for(intI=0; i<threadnum; ++i)//create thread at     { - Threadarray.emplace_back (Threadfun, i); -     } -      for(intI=0; I<threadarray.size (); ++i)//recycle thread -     { - Threadarray[i].join (); in     } -cout<<"I am Main thread, n="<<N<<Endl; to     return 0; +}

C++11 new features atomic and thread

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.