我正在迭代双向数据结构.我可以用(做,要么++,--)或(std::prev,std::next,std::advance).使用较晚的优势是否有优势?
我有简单的类Hello,我试图say_hello在不同的线程上调用成员函数.我创建了两个不同的实现它hellos_in_stack和hellos_in_heap.hellos_in_heap按预期工作但是hellos_on_stack在成员变量上有竞争条件_i.如何在堆栈中避免使用它mutex?
#include <thread>
#include <iostream>
#include <vector>
#include <mutex>
std::mutex mu;
class Hello
{
int _i;
public:
Hello()
{
std::lock_guard<std::mutex> lock(mu);
_i = 0;
}
~Hello(){
}
void say_hello()
{
std::lock_guard<std::mutex> lock(mu);
std::cout << "say_hello from thread " << ++_i << " " <<this << " " << std::this_thread::get_id() << std::endl;
}
};
void hellos_in_stack()
{
std::vector<std::thread> threads;
for(int i = 0; i < …Run Code Online (Sandbox Code Playgroud)