【发布时间】:2019-07-10 11:56:24
【问题描述】:
我将std::sub_match 作为参数传递给std::thread(请参阅下面的示例代码)。线程函数需要一个 const 字符串引用。 sub_match 可以转换为字符串。所以一切编译正常。
但有时函数接收到错误的字符串。 当我在将 sub_match 传递给线程之前将其转换为字符串时,它会按预期工作。有什么区别?
我认为这是一个竞争条件,因为当线程执行时,原来的 sub_match 可能不再存在。但我认为线程的参数无论如何都会被复制。 如何找出哪些参数可以安全地传递给线程,哪些不能?
#include <iostream>
#include <string>
#include <vector>
#include <thread>
#include <regex>
#include <unistd.h>
class test_t {
public:
test_t(void) {}
~test_t(void) {}
void start(void){
//-------------------------------------------------
// Do some memory allocation.
// The error seems to appear faster with that.
std::vector<std::string> vec;
for(unsigned int i = 0; i < 1000; ++i) {
vec.push_back("test_test_test");
}
//-------------------------------------------------
std::string event = "operating";
std::smatch match;
std::regex expr("\\(operating\\)",
std::regex_constants::icase |
std::regex_constants::basic);
if(std::regex_match(event, match, expr)) {
std::cout << "start thread" << std::endl;
m_thread = std::thread(&test_t::thread_func, this, match[1]); //NOK
// m_thread = std::thread(&test_t::thread_func, this, match[1].str()); // OK
// m_thread = std::thread(&test_t::thread_func, this, (std::string)match[1]); // OK
m_thread.detach();
std::cout << "thread started" << std::endl;
}
}
private:
std::thread m_thread;
void thread_func(const std::string& string) {
if(string != "operating") {
std::cout << "ERROR: string: \"" << string << "\"" << std::endl;
exit(EXIT_FAILURE);
} else {
std::cout << "string: \"" << string << "\"" << std::endl;
}
}
};
int main(int argc, char** argv) {
test_t test;
while(1) {
test.start();
usleep(100);
}
return 0;
}
编译消息:
Compiled with: g++ --std=c++11 -pthread -o test main.cpp
g++ --version: g++ (SUSE Linux) 4.8.5
预期输出:
start thread
thread started
string: "operating"
(repeat)
实际输出:
start thread
thread started
string: "operating"
ERROR: string: "test_test"
【问题讨论】:
-
match[1]返回一个常量引用,对吧?所以,你应该这样传递它,使用std::cref(match[1]),因为std::thread移动它的所有参数。
标签: c++ multithreading c++11