I would like to start multiple threads using a sample code like below:
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);
}
}
However, I can't get this to work (bad allocation error). What am I doing wrong?
You cannot pass a string as you are doing, but you can pass a string pointer. BUT! You have to be careful that the string stays valid at least until the threads starts... This is usually done by creating the strings on the heap, using
new, but it can also work using global objects. Here's how your code could work.