jeudi 16 novembre 2023

Why does std::mutex make things wrong here?

I edit code in VS (not vs code), and run it in WSL 2.


#include <iostream>
#include <deque>
#include <vector>
#include <list>
#include <mutex>
#include <condition_variable>
#include <string.h>


const int a = 10000;
const int b = 20000;

class myclass
{
public:
    myclass(int sz1, int sz2) :s1(sz1, '\0'), s2(sz2, '\0')
    {
        std::cout << "constructor\n";
    }
private:
    std::string s1, s2;
    std::mutex m1, m2;
};

int main()
{
    std::vector<myclass> m;
    for (int i = 0; i < 10000; i++)
    {
        m.emplace_back(a, b);
    }
    std::cout << m.size();
    return 0;
}

For code above, there are some errors when build.

But if I comment out std::mutex m1, m2;, it works well. So it seems like it is caused by mutex. Why?

Thank you for your help.

Aucun commentaire:

Enregistrer un commentaire