线程函数中的c++参数更改

c++ argument changes in thread function

本文关键字:参数 c++ 函数 线程      更新时间:2023-10-16

我正在编写一个Android应用程序,它读取c++(NDK(中的文本文件。

我将文件listassets文件夹复制到/data/user/0/my-package/files/list,在那里我可以用我的本地代码读取,复制完成后或如果目标文件存在,我会执行以下操作:

const char* fileName = env->GetStringUTFChars(_name, nullptr);
const char* filePath = env->GetStringUTFChars(_destination, nullptr);
if(copy_file(AAssetManager_fromJava(env, manager),fileName, filePath)){
Reader *r = new Reader();
log("Initializing reader with file: %s",filePath);
thread t(&Reader::read, r, filePath);
t.detach();// will crash if no detach, join() will block the UI thread.
}

我的Reader::read:

void Reader::read(const char* filePath){
log("Reading from file: %s",filePath);
ifstream infile(filePath);
string line;
while(infile>>line){
// read logic ...
}
}

我得到不同的输出,有时

Initializing reader with file: /data/user/0/my-package/files/list
Reading from file: /data/user/0/my-package/files/list

一切都按预期进行但是有时我会收到

Initializing reader with file: /data/user/0/my-package/files/list
Reading from file: /data/user/0/my-package/files

看到了吗?文件路径似乎被切断了,我的ifstream正在尝试读取目录files

我被告知,默认情况下,参数filePath将按值传递给线程,并且没有其他线程使用该变量,线程初始化后filePath发生的唯一情况是:

env->ReleaseStringUTFChars(_destination, filePath);

我已经尝试了许多不同的方法来将文件路径传递给新线程,如果我像这样传递filePathstd::ref(filePath),我会在read函数中得到空字符串,因为变量已经在外部清除。

对此有什么建议吗?

在线程完成之前调用ReleaseStringUTFChars将是灾难性的,因为filePath指向的内存也将被释放。如果您不完全理解指针和内存处理是如何工作的,我建议使用类似于std::string的东西,而不是constchar*,并将该字符串传递给您的函数。