C++11新特性atomic和thread

  今天才发现C++11原来支持原子操作,还支持thread类创建线程,真的是越来越6了。之前做项目的时候创建线程都是用POSIX标准的pthread_create函数,然后线程同步一般用的都是pthread_mutex。今天又get了一个新技能,可以用thread类来创建线程,用atomic_flag实现自旋锁来进行线程同步,不说了不说了,赶紧拿小本本记下来:

 1 #include<iostream>
 2 #include<vector>
 3 #include<thread>
 4 #include<atomic>
 5 using namespace std;
 6 long N=0;
 7 std::atomic_flag lock=ATOMIC_FLAG_INIT;
 8 void threadFun(int n)//线程入口函数
 9 {
10     for(int i=0; i<10000000; ++i)
11     {
12         while(lock.test_and_set());//自旋锁
13         ++N;
14         lock.clear();
15     }
16 }
17 int main()
18 {
19     vector<thread> threadArray;
20     int threadNum=2;
21     cout<<"I am main thread, N="<<N<<endl;
22     for(int i=0; i<threadNum; ++i)//创建线程
23     {
24         threadArray.emplace_back(threadFun, i);
25     }
26     for(int i=0; i<threadArray.size(); ++i)//回收线程
27     {
28         threadArray[i].join();
29     }
30     cout<<"I am main thread, N="<<N<<endl;
31     return 0;
32 }

 

posted @ 2018-03-17 16:20  jeysin  阅读(346)  评论(0编辑  收藏  举报