gpt4 book ai didi

c++ - 字符串流和多线程

转载 作者:太空狗 更新时间:2023-10-29 23:43:57 25 4
gpt4 key购买 nike

我是多线程和 C++ 的新手,尝试在我的应用程序中使用线程来保存文件时遇到问题。代码如下:

#include <iostream>
#include <thread>
#include <fstream>
#include <vector>
#include <sstream>

using namespace std;

void writeCSV(vector<vector<double> > & vec, const char* filename) {

ofstream output(filename);

for (vector<vector<double> >::const_iterator i = vec.begin(); i != vec.end(); ++i) {
for (vector<double>::const_iterator j = i->begin(); j != --i->end(); ++j) {
output << *j << ", ";
}
output << *(--i->end()) << "\n";
}


}

void testFn(int id) {
std::ostringstream filename;
vector<vector<double> > v(460, vector<double>(460,0));
filename << "test" << id << ".csv";
const char* fileStr = filename.str().c_str();
cout << id << " : " << fileStr << endl;
writeCSV(v, fileStr);

}


int main() {

int numOfThreads = 180;
std::thread t[numOfThreads];


for (int i= 0; i< numOfThreads; i++) {
t[i] = std::thread (testFn, i);
}

for (int i = 0; i< numOfThreads; i++) {
t[i].join();
}

return 0;

}

当我运行这个程序时,它在终端中打印出来(结果的子部分):

66 : 0�c
97 : test97.csv
90 : �'�dz
85 : �'�dz
43 :
9695 : �'�dz
67 : �'�dz
93 :
: �_ ��
115 : test115.csv
144 : test144.csv
99 : test99.c0
68 :
91 : )�
98 : test98.c0

以及用奇怪/错误的文件名保存文件。我猜这似乎是多线程和 ostringstream 的一个问题,但是有什么想法为什么/如何解决吗?

最佳答案

这与多线程无关。

const char* fileStr = filename.str().c_str();

std::ostringstreamstr() 方法返回表示字符串流内容的 std::string

std::stringc_str() 方法返回一个指向字符串数据的内部指针。

您缺少的是 c_str() 返回的指针仅在 std::string 被修改或被销毁之前有效,以两者为准先来。

这里 std::string 被立即销毁,因为它是一个临时值。因此,指向其内部数据的指针会立即失效。

您必须将返回的字符串存储在一个对象中,只要需要字符串数据,该对象就存在。简单地:

std::string str = filename.str();
const char* fileStr = str.c_str();

str 在其自 Action 用域的剩余部分继续存在,这里足够长。

关于c++ - 字符串流和多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38204879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com