Two threads operate a std::deque, does below code have race condition?

56 views Asked by At

I have a small test to test if std::deque in my code have race condition/undefined behavior

num = 10000;
m = 0;
n = 0;
void push()
{
    while(num--) {
        {
            q.push_back(m);
        }
        printf("push succ: %d\n", m);
        //cout << "push succ: " << m << endl;
        m++;
        
        std::this_thread::sleep_for(std::chrono::microseconds(4000));
    }
    cout << "m: " << m << endl;
}

void pop()
{
    while(true) {
        if (!q.empty()) {
            //cout << "q.size() " << q.size() << endl;
            printf("front: %d\n", q.front());
            {
                n++;
                q.pop_front();
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(4));
        }

        cout << "n: " << n << endl;
        if (stop && q.empty()) 
            break;        
    }
}

one thread push element, and the other pops element. n and m will record the operation times, I expect every element will be pushed once and be poped once. I run it on my MacOS, it sometimes will have duplicate element or missed element. I also run it on linux, but it's hard to reproduce.... I thought it's no problem if I check empty() before pop_front at first. But it seems not like this. I check the STL code, but not go through very deeply, still have no idea about the reason.enter image description here

0

There are 0 answers