0

Supposing all the operation I can do is either:

  • Inserting new element into an std::list (or)
  • Reading the back() element of the list

Am I thread safe? Any thread can do any of the two operations in any order. I'm not expecting any specific order to see, for eg if I insert an element and then read the back() I am NOT expecting it to be the last one I just inserted, all I need is that the returned element shall be a valid one.

Can I safely do this without introducing an undefined behavior? Also I know I may need to use a concurrent queue, that's an option too I may consider, but this time I'm purely curious about this specific case with an std::list.

original.roland
  • 640
  • 5
  • 17
  • Possible duplicate https://stackoverflow.com/questions/12931787/c11-stl-containers-and-thread-safety . For your concrete list-insertion-case: No, you cannot expect thread-safety here since it's a container-distinct operation, not an element-distinct one. – Secundi Jan 15 '21 at 09:17
  • That link is rather narrowing the scope of only accessing the elements, which is not necessarily the case here. – original.roland Jan 15 '21 at 10:26

1 Answers1

1

Am I thread safe?

Potentially yes; Not necessarily.

It is crucial where the element is inserted. If you insert to the back of the list, then you have a data race, and therefore UB. If you insert elsewhere other than the end (and therefore the list must be non-empty prior to insert), then it should be thread safe.

eerorika
  • 232,697
  • 12
  • 197
  • 326