你不能像你正在做的那样传递一个字符串,但你可以传递一个字符串指针。 但!您必须注意字符串至少在线程启动之前保持有效......这通常通过在堆上创建字符串来完成,使用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;
}