简体   繁体   English

在线程中使用 std::string 函数是否安全? (c++)

[英]is it safe to use std::string functions in a thread? (c++)

i want to make a thread in a dll that will make some web requests.我想在 dll 中创建一个线程,该线程将发出一些 web 请求。 in the thread now i use std::sting functions (c_str(), at(), find(), substr()) and (string + string).在线程中,我现在使用 std::sting 函数(c_str()、at()、find()、substr())和(string + string)。 as i know the threads running asynchronously, and also i found out if i call 1 function 2 times at the same time(1 from main program and 1 from thread) will cause problems/crash i guess because both using the same memory?我知道线程异步运行,而且我发现如果我同时调用 1 function 2 次(1 次来自主程序,1 次来自线程)会导致问题/崩溃,我猜是因为两者都使用相同的 memory?

so now if i do many web requests very fast i crash sometimes.所以现在如果我做很多 web 请求非常快,我有时会崩溃。 i think it's because using at the same time 2 times a std::string function.我认为这是因为同时使用 2 次 std::string function。 Also if this is maybe cause the problem is there any other way i can use for that work?另外,如果这可能是导致问题的原因,我还有其他方法可以用于该工作吗?

Are you sharing the same std::string object across two threads?您是否跨两个线程共享相同的std::string object If so (and that object is being modified by one thread while the other thread is also trying to use it), that would cause undefined behavior, unless you protect those accesses with some form of synchronisation (such as a mutex ).如果是这样(并且 object 正在被一个线程修改,而另一个线程也在尝试使用它),那将导致未定义的行为,除非您使用某种形式的同步(例如mutex )保护这些访问。

If OTOH the two threads are each operating on their own separate/private std::string objects, that won't cause a problem.如果 OTOH 两个线程都在各自独立/私有的std::string对象上运行,则不会导致问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM