多线程-作为参数传递的常量字符数组

Multithreading - const char array passed as parameter

本文关键字:常量 字符 数组 参数传递 多线程      更新时间:2023-10-16

我有一个函数如下:

laodFunc(const map<uint16_t, string> & pClasses, const char * pFilePath);

我这样称呼它。为了将其作为一个新线程与boost 一起运行

boost::thread_group g;
stringstream myStr;
......
boost::thread *new_thread = new boost::thread(&loadFunc,classes,myStr.str().c_str());
 g.add_thread(new_thread);

但是当我在调用的方法中显示给定的路径(char*)时,我得到了错误的内容:路径

我想知道我在这里做错了什么。感谢

myStr.str().c_str()引用的内存被立即销毁(因为myStr.str()返回的临时std::string被销毁),因此线程正在取消对悬挂指针的引用(导致未定义的行为)。

要进行更正,请确保提供给laodFunc()的指针在线程的生存期内保持有效。或者,将const char* pFilePath更改为std::string const& pFilePath:

loadFunc(const map<uint16_t, string> & pClasses, std::string const& pFilePath);
boost::thread *new_thread = new boost::thread(&loadFunc, classes, myStr.str());

CCD_ 7的副本将存储在内部并传递给线程函数(请参阅带参数的线程构造函数)。即使loadFunc()的参数类型是const&classes参数也将被复制,这毫无意义。如果需要,可以使用boost::cref():来避免此副本

boost::thread *new_thread = new boost::thread(&loadFunc,
                                              boost::cref(classes),
                                              myStr.str());

由于myStr要么是多个线程使用的全局变量(因此您可以获得"变量的最新设置"的值),要么是使用后"消失"的局部变量,因此您需要采取措施使其持久化并在每个线程中唯一。这里不完全清楚您的目的是什么,而是"每个线程"对象,该对象包含与线程一起创建的字符串,并在线程被销毁时被销毁。