小编uka*_*aku的帖子

为什么这段C++代码不同步

我正在学习编写多线程应用程序.因此,即使使用互斥锁,我也希望我的线程能够访问简单的共享资源.

例如,考虑以下代码:

using namespace std;
mutex mu;
std::vector<string> ob;

void addSomeAValues(){
    mu.lock();    
    for(int a=0; a<10; a++){
        ob.push_back("A" + std::to_string(a));
        usleep(300);    
    }
    mu.unlock();
}

void addSomeBValues(){    
    mu.lock();    
    for(int b=0; b<10; b++){            
        ob.push_back("B" + std::to_string(b));        
        usleep(300);    
    }   
    mu.unlock();
}

int main() {    
    std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();        
    thread t0(addSomeAValues);        
    thread t1(addSomeBValues);    
    std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();

    t0.join();
    t1.join();

    //Display the results
    cout << "Code Run Complete; results: \n";    
    for(auto k : ob){
        cout << k <<endl;
    }
    //Code running complete, report the time it …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading synchronization mutex

5
推荐指数
1
解决办法
525
查看次数

标签 统计

c++ ×1

multithreading ×1

mutex ×1

synchronization ×1