#include <iostream>
#include <thread>
#include <mutex>
#include <atomic>
using namespace std;
mutex mtx;
int n = 0;
void add_lock_guard(int si, int sj, int &res)
{
cout << "111 add_lock_guard 111" << endl;
for (int i = si; i < sj; i++)
{
lock_guard<mutex> lock(mtx);
res += i;
}
}
void thread_lock_test()
{
int ress[10] = {0};
thread ths[10];
int k = 0;
for (thread &th : ths)
{
th = thread(add_lock_guard, 1, 11, ref(ress[k++]));
}
for (thread &th : ths)
{
th.join();
}
int sum = 0;
for (int i = 0; i < 10; i++)
{
sum += ress[i];
}
cout << "sum=" << sum << endl;
cout << "main proc end" << endl;
}
int main()
{
thread_lock_test();
return 0;
}
/*
111 add_lock_guard 111111 add_lock_guard 111
111 add_lock_guard 111
111 add_lock_guard 111
111 add_lock_guard 111
111 add_lock_guard 111
111 add_lock_guard 111
111 add_lock_guard 111
111 add_lock_guard 111
111 add_lock_guard 111
sum=550
main proc end
*/
c++ thread 引用传参示例
最新推荐文章于 2024-08-21 18:16:36 发布