简体   繁体   中英

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. in the thread now i use std::sting functions (c_str(), at(), find(), substr()) and (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?

so now if i do many web requests very fast i crash sometimes. i think it's because using at the same time 2 times a 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? 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 ).

If OTOH the two threads are each operating on their own separate/private std::string objects, that won't cause a problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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