C++ 多个线程能否修改C+;的同一个私有成员+;通过调用该对象的相同方法来创建该对象?
C++ 多个线程能否修改C+;的同一个私有成员+;通过调用该对象的相同方法来创建该对象?,c++,multithreading,C++,Multithreading,KMeans::Start方法需要访问KMeans类的私有字段。我的问题是:这些线程是在同一个KMeans对象上运行,还是在不同的对象上运行?它们在同一个实例上运行,因为您通过引用传递KMeans(使用std::ref)。通过在Start()中打印This很容易确认: 谢谢,你的回答很有帮助! file1.hpp: class KMeans { public: KMeans(); virtual ~KMeans(); void Start(); private: std::a
KMeans::Start
方法需要访问KMeans
类的私有字段。我的问题是:这些线程是在同一个KMeans
对象上运行,还是在不同的对象上运行?它们在同一个实例上运行,因为您通过引用传递KMeans
(使用std::ref
)。通过在Start()
中打印This
很容易确认:
谢谢,你的回答很有帮助!
file1.hpp:
class KMeans {
public:
KMeans();
virtual ~KMeans();
void Start();
private:
std::atomic<int32_t> thread_counter_;
std::unique_ptr<boost::barrier> process_barrier_;
// ============ PS Tables ============
petuum::Table<float> centres_;
int examples_per_batch_;
int examples_per_thread_;
};
file2.cpp:
int main(){
KMeans kmeans;
std::vector<std::thread> threads(FLAGS_num_app_threads);
for (auto& thr : threads) {
thr = std::thread(&KMeans::Start, std::ref(kmeans));
}
}
std::thread(&KMeans::Start, std::ref(kmeans));
KMeans::Start()
{
std::cout << this << std::endl;
}
std::thread(&KMeans::Start, kmeans);