I want to make std::string append function thread safe, because I am appending a specific string from different threads.
I'm a quite beginner in c++ so I'm not sure what problems this may rise.
The solution I am thinking about is instead of using somestring.append("appendthis");
Use the following code:
bool appendtsReady = true; void appendts(std::string& originalString, char* app) { while (!appendtsReady) {} appendtsReady = false; originalString.append(app); appendtsReady = true; } appendts(somestring, "appendthis"); I would hope that if the string is being appended the new request appendts(somestring, "appendthis_from_different_thread"); will be caught on loop until previous append is finished.
Is this solution is too naive?
whilestatement's conditional will never betrueand remove that code.volatileto the flag might help, but a proper lock would be vastly better.