64,647
社区成员
发帖
与我相关
我的任务
分享
#include <iostream> // std::cout
#include <atomic> // std::atomic
#include <thread> // std::thread
#include <vector> // std::vector
struct C : std::atomic<int> {
C() : std::atomic<int>(0) {}
void increase_member (int n) { for (int i=0; i<n; ++i) fetch_add(1); }
};
int main ()
{
std::vector<std::thread> threads;
std::cout << "increase counter (bar) with 10 threads using member...\n";
C bar;
for (int i=1; i<=10; ++i)
threads.push_back(std::thread(&C::increase_member,std::ref(bar),1000));
std::cout << "synchronizing all threads...\n";
for (auto& th : threads) th.join();
std::cout << "bar: " << bar << '\n';
return 0;
}
std::thread(&C::increase_member, std::ref(bar), 1000) // std::ref()
C++11的std::thread构造函数不支持std::ref的这种用法。
你可以认为这是C++11标准的一个缺陷(LWG #2219)。不幸的是GCC 4.8很积极地迎合了标准。
目前,你可以用传指针的方式:
std::thread(&C::increase_member, &bar), 1000)
或者用std::bind、lambda等解决。#include <iostream> // std::cout
#include <atomic> // std::atomic
#include <thread> // std::thread
#include <vector> // std::vector
struct C : std::atomic<int> {
C() : std::atomic<int>(0) {}
void increase_member (int n) { for (int i=0; i<n; ++i) fetch_add(1); }
};
int main ()
{
std::vector<std::thread> threads;
std::cout << "increase counter (bar) with 10 threads using member...\n";
C bar;
for (int i=1; i<=10; ++i)
threads.push_back(std::thread([&bar](){bar.increase_member(1000);}));
std::cout << "synchronizing all threads...\n";
for (auto& th : threads) th.join();
std::cout << "bar: " << bar << '\n';
return 0;
}