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;
}
我想使用如下示例代码启动多个线程:
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;
}