Std :: queue pop push thread security

Basically my question is, is it safe to call front + pop and push from two threads without syncing? I've read about this and haven't found a clear answer. People say that you should use a mutex, but some hint that you can use two different mutexes for push and pop. It's true?

Does this code have undefined behavior?

std::queue<int> queue;

int pop()
{
    int x = queue.front();
    queue.pop();
    return x;
}

void push(int x)
{
    queue.push(x);
}

int main()
{
    queue.push(1);
    std::thread t1(pop);
    std::thread t2(push);

    t1.join();
    t2.join();
}

      

I would say this behavior is undefined, but you can create a safe pop push queue, so why not std :: queue like this?

+3


source to share


1 answer


No no. Standard containers are not thread safe - you cannot mutate them from two threads. You will need to use a mutex or non-blocking queue. The problem is that it std::queue

should work with objects such as std::string

, which cannot be atomically moved or constructed, and std::queue

should also support arbitrary sizes.



Most unencrypted queues only work with machine word sizes and a fixed maximum size. If you want flexibility std::queue

and thread safety, you will have to manually use a mutex. Adding a mutex to the default implementation would also be extremely useless, as now all of a sudden every application will have thread safety even if it doesn't need it.

+7


source







All Articles