многопоточность — c ++ _beginthread не может передать строку в качестве параметра

Я хотел бы начать несколько потоков, используя пример кода, как показано ниже:

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);
}
}

Тем не менее, я не могу заставить это работать (неправильная ошибка размещения). Что я делаю неправильно?

-1

Решение

Вы не можете передать строку, как вы делаете, но вы можете передать указатель на строку. НО! Вы должны быть осторожны, чтобы строка оставалась действительной, по крайней мере, до тех пор, пока не начнутся потоки … Обычно это делается путем создания строк в куче, используя 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;
}
1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector