在不使用互斥锁的多线程中将元素添加到std :: list的c ++

时间:2018-08-09 10:24:39

标签: c++ multithreading stdlist

对于当前代码,输出将显示不同的ml大小。我对此程序不会崩溃而感到困惑,并且多线程尝试更改list_thread_safe中的列表。 std :: list如何在c ++中处理此问题?首先谢谢。

(有关互斥量的注释代码,它将获得相同的ml大小。)

#include <iostream>
#include <thread>
#include <string>
#include <vector>
#include <map>
#include <unistd.h>
#include <list>
#include <mutex>
#include <algorithm>

std::mutex list_mutex; 
class list_thread_safe {
public:
    list_thread_safe() {
        std::cout<<"construct a list thread safe"<<std::endl;
    }

    ~list_thread_safe() {
        std::cout<<"destruct a list thread safe"<<std::endl;

    }

    void add_to_list(int new_v) {
        // std::lock_guard<std::mutex> guard(list_mutex);

        // add 10 elements to list 
        l.push_back(new_v);    
        l.push_back(new_v);  
        l.push_back(new_v);    
        l.push_back(new_v);     
        l.push_back(new_v);    
        l.push_back(new_v);  
        l.push_back(new_v);    
        l.push_back(new_v); 
        l.push_back(new_v);    
        l.push_back(new_v);  
    }
    std::list<int> l;

};

void add1_times(list_thread_safe& lts,int thread_num, int n) {
    for (int i=0; i< n ; i++) {
        lts.add_to_list(i);
    }
    std::cout<<"thread num "<<thread_num<<" done "<<std::endl;
    std::cout<<"thread list size: "<<lts.l.size()<<std::endl;

}
int main(){
    list_thread_safe ml;
    std::vector<std::thread> ths;
    int thread_num = 10;
    int add_num = 20;
    for(size_t i = 0; i < thread_num; i++)
    {
      printf("%d ", i);
      ths.push_back(std::thread(std::bind(add1_times, std::ref(ml), i, add_num)));
    }

    std::for_each(ths.begin(), ths.end(), std::mem_fn(&std::thread::join));
    std::cout<<"ml size:"<<ml.l.size()<<std::endl;

}

1 个答案:

答案 0 :(得分:0)

“ ... std :: list如何处理此问题...”

std::list不是线程安全的。在多个线程上读取std::list是安全的。  但是让多个线程修改列表,或者一个线程修改列表和多个读者是不安全的。