[英]How can I modify a string from a thread?
我正在嘗試從線程中修改一些字符串(每個線程都有其自己的字符串),但是所有字符串都存儲在向量中,因為在線程完成其操作后,我需要能夠訪問它們。
我沒有在c ++中使用線程,所以如果這樣做很糟糕,歡迎所有建議:)
基本上,程序現在唯一要做的是:
這給出了一個段錯誤:(
這只是一個不好的方法嗎? 我還能怎么做?
static const int cores = 8;
void bmh_t(std::string & resr, int tid){
resr.append(std::to_string(tid));
resr.append(",");
return;
}
std::vector<std::string> parbmh(std::string text, std::string pat){
std::vector<std::string> distlists;
std::thread t[cores];
//Launch a group of threads
for (int i = 0; i < cores; ++i) {
distlists.push_back(" ");
t[i] = std::thread(bmh_t,std::ref(distlists[i]), i);
}
for (int i = 0; i < cores; ++i) {
t[i].join();
}
return distlists;
}
您的基本方法很好。 編寫並行代碼時,您需要考慮的主要事情是,線程之間共享的任何數據都是以安全的方式完成的。 因為您的算法為每個線程使用不同的字符串,所以這是一種很好的方法。
您看到崩潰的原因是因為您已經在給每個線程一個對存儲在矢量中的數據的引用之后,在字符串矢量上調用push_back。 這是一個問題,因為push_back的大小達到其容量時就需要增大其向量。 這種增長會使您分派給每個線程的引用無效,從而導致它們寫入已釋放的內存。
修復非常簡單:只需提前確保向量不需要增長即可。 這可以通過指定初始數量的元素的構造函數參數來完成。 調用reserve(); 或調用resize()。
這是一個不會崩潰的實現:
static const int cores = 8;
void bmh_t(std::string & resr, int tid){
resr.append(std::to_string(tid));
resr.append(",");
return;
}
std::vector<std::string> parbmh(){
std::vector<std::string> distlists;
std::thread t[cores];
distlists.reserve(cores);
//Launch a group of threads
for (int i = 0; i < cores; ++i) {
distlists.push_back(" ");
t[i] = std::thread(bmh_t, std::ref(distlists[i]), i);
}
for (int i = 0; i < cores; ++i) {
t[i].join();
}
return distlists;
}
在線程可以對包含的字符串起作用之前,將對字符串向量進行破壞。 您需要在返回之前加入線程,以免破壞字符串向量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.