使用多线程向同一个STL容器尾部并行插入新元素,在不进行同步管理的情况下,会出现未定义的行为。这里使用std::lock_guard进行同步管理

举例:

#include "boost/asio/thread_pool.hpp"
#include "boost/thread.hpp"
#include "boost/asio.hpp"
#include <thread>
#include <list>
#include <iostream>
#include <mutex>

void test() {
    int num = std::thread::hardware_concurrency();

    std::cout << num << std::endl;

    boost::asio::thread_pool pool(num);
    std::list<int> l;
    std::mutex m;
    for(int i = 0; i < 20; i++) {
        boost::asio::post(pool, [&l, i, &m] () {
            std::lock_guard<std::mutex> lock(m);
            l.emplace_back(i);
        });        
    }
    pool.join();
    std::cout << l.size() << std::endl;
    for(auto x : l) {
        std::cout << x << " ";
    }
    std::cout << std::endl;
}

int main() {
    for(int i = 0; i < 10; i++) {
        test();
        std::cout << i << std::endl << std::endl;
    }
    return 0;
}

其中,在创建std::lock_guard实例之后,加锁处理,在超出std::lock_guard实例作用域范围之后,自动解锁处理

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐