使用pthreads时奇怪的std::string行为
Bizzare std::string behavior when using pthreads
我有一个奇怪的std::string问题。它与通过线程在结构中传递字符串有关。本质上,我通过连接字符串向量来构建字符串,并使用这个构建的字符串作为结构中的字符串。然后将结构体作为参数传递给线程,访问string成员变量,并尝试打印它。出现了令人难以置信的行为:
如果在线程创建之前先打印字符串,那么在线程运行时打印字符串。但是,如果在线程创建之前没有打印字符串,那么在线程运行时字符串不会打印,并且字符串的大小为0。有人能帮我解决这个问题吗?
#include <iostream>
#include <pthread.h>
#include <string>
#include <vector>
struct data
{
std::string msg;
int id;
};
std::string GetString(std::vector<std::string> &args);
void *F(void *vargp);
int main()
{
using std::cout;
using std::endl;
std::vector<std::string> args;
args.push_back(std::string("skip"));
args.push_back(std::string("one"));
args.push_back(std::string("two"));
args.push_back(std::string("three"));
args.push_back(std::string("four"));
args.push_back(std::string("five"));
data d;
d.id = 123;
d.msg = GetString(args);
/* Removing the below commented line escapes the error.
* With the line commented the string has size 0 in F.
* However when it is compiled and run, the string in F
* has its actual size and the correct output appear.
* WHAT IS GOING ON?
*/
// cout << "before: " << d.msg << endl;
pthread_t tid;
pthread_create(&tid, NULL, F, &d);
pthread_exit(0);
}
void *F(void *vargp)
{
using std::cout;
using std::endl;
pthread_detach(pthread_self());
data d = *(data *)vargp;
cout << d.msg << " " << d.id << endl;
}
std::string GetString(std::vector<std::string> &args)
{
std::string str(args[1]);
for (int i=2; i!=args.size(); i++)
str += " " + args[i];
return str;
}
我通过
编译函数g++ test.cpp -pthread -o test
这是由于未定义的行为,因为变量d
超出了作用域并在main
函数中执行pthread_exit
时被破坏。一旦原始变量超出作用域,线程函数中的指针就不再有效。
对于一个中间解决方案,动态地分配d
。对于长期的解决方案,可以考虑使用std::thread
。
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
- 将C++ std::string 转换为 UTF-16-LE 编码的字符串
- 重载 + 自己的类和 std::string 的运算符
- 如何使用 std::string 作为 QHash 的键?
- 将日语 wstring 转换为 std::string
- 可以从std::string继承以提供类型一致性吗
- 构造函数采用std::string_view与std::string并移动
- 在共享缓冲区内存中创建 ::std::string 对象
- std::string.size() 未知行为
- Valgrind 在 std::string::swap 中报告 SIGILL