C++ _beginthread不能将字符串作为参数传递
c++ _beginthread can't pass string as a parameter
我想使用如下所示的示例代码启动多个线程:
void ThreadFunction(void* param) {
cout << (string)param << endl;
_endthread();
}
int main(int argc, char* argv[]) {
for (unsigned int i = 1; i <= 10; i++) {
string String = "This is test nr ";
String += i;
_beginthread(ThreadFunction, 0, (void*)&String);
}
}
但是,我无法让它工作(错误的分配错误(。我做错了什么?
不能像现在这样传递字符串,但可以传递字符串指针。但!您必须注意字符串至少在线程启动之前保持有效...这通常是通过使用new
在堆上创建字符串来完成的,但它也可以使用全局对象。 以下是代码的工作原理。
#include <unistd.h>
#include <string>
#include <vector>
#include <sstream>
#include <pthread.h>
void ThreadFunction(void* param)
{
std::string* s = reinterpret_cast<std::string*>(param);
cout << *s << endl;
} // <-- no need to call endthread when exiting gracefully
std::vector<std::string> myStrings;
int main(int argc, char* argv[])
{
// since we will use pointers to strings in the vector myStrings,
// we need to be sure it is final before using them.
// you could store some form of smart pointer in the vector to avoid
// this issue
for (unsigned int i = 0; i < 10; i++)
{
std::stringstream ss;
ss << "This is test nr " << i;
myStrings.emplace_back(ss.str());
}
for (unsigned int i = 0; i < myStrings.size(); i++)
{
_beginthread(FunctionName, 0, &myStrings[i]);
}
// we must pause this thread and wait a little while for the threads
// to run. _beginthread does not block, and exiting the program too
// quickly would prevent our background threads from executing...
sleep(1);
return 0;
}
相关文章:
- 将字符串数组作为函数参数传递
- 如何通过C++在Python函数中传递字符串参数
- 当数组大小在C++中未知时,如何在运行时将对字符串数组的引用作为函数参数传递?
- 如何将从第 2 个字符开始的字符串作为函数中的参数传递以进行递归,并约束数据 tiee 是函数中的字符串?
- C++ _beginthread不能将字符串作为参数传递
- 如何将 std::string 作为构造函数参数传递,并将其保存的 C 字符串存储在 void 指针中?
- Pybind11:将字符串*参数传递给构造函数
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 在 c++ 中调用将字符串作为参数传递的函数时出错
- 无法将字符串参数传递到构造函数中?
- 将文本字符串作为常量字符 * 参数传递会导致代码分析器错误
- 如何在C++中将字符串的动态二维数组作为参数传递
- 减少将参数传递给函数所需的字符串流操作的详细程度
- 如何将字符串数组作为函数参数传递
- 将字符串作为系统参数C 传递
- 将字符串作为命令行参数传递
- 线程传递字符串参数的布尔函数
- 试图将字符串作为类的参数传递,但在C++中它被识别为字符数组
- 如何确保当无效字符串作为参数传递时posix_time_zone构造函数不会崩溃
- C++ 不能将公共 const 字符串成员作为参数传递给同一类的成员函数