Reputation: 441
I have a small question about threading in Windows. I have the following code :
main.cpp
int main(int ac, char **av)
{
std::vector<Mthread *> mythread;
std::list<std::string> stack;
DWORD id = 0;
stack.push_back("Maison");
stack.push_back("Femmes");
stack.push_back("Fetes");
stack.push_back("Voitures");
stack.push_back("Nounours");
while (id != 5)
{
mythread.push_back(new Mthread());
mythread[mythread.size() - 1]->initThread(&stack, id);
id++;
}
id = 0;
while (id != 5)
{
WaitForInputIdle(mythread[id]->getThread(), INFINITE);
id++;
}
return (1);
}
and Mthread.cpp who is creating my Mthread
class.
Mthread::Mthread() {}
Mthread::~Mthread() {}
HANDLE Mthread::getThread(void) const
{
return (this->thread);
}
bool Mthread::initThread(std::list<std::string> *list, DWORD ID)
{
this->save = list;
this->thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Mthread::ThreadFunc, (LPVOID)list, 0, &ID);
if (this->thread == NULL)
{
std::cout << "Erreur lors du lancement du thread" << std::endl;
return (false);
}
else
{
return (true);
}
}
void Mthread::ThreadFunc(LPVOID list)
{
std::cout << " is launch" << std::endl;
}
The code is working, but I have a small problem : no string is written on the terminal. But, if I change my code to :
bool Mthread::initThread(std::list<std::string> *list, DWORD ID)
{
this->save = list;
this->thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Mthread::ThreadFunc, (LPVOID)list, 0, &ID);
if (this->thread == NULL)
{
std::cout << "Erreur lors du lancement du thread" << std::endl;
return (false);
}
else
{
std::cout << "OK" << std::endl;
return (true);
}
}
Well "OK" and "is launch" is written 5 times on the terminal. I don't understand why.
When I pass a small string a to cout
it seems to be working, but when I don't nothing is written.
Upvotes: 0
Views: 252
Reputation: 860
Before terminating, your program should wait until the threads have finished their job. On windows, take a look at WaitForMultipleObjects.
Upvotes: 1
Reputation: 4869
short answer: I guess your main() terminates before the threads have a chance to run. add a sleep() or something similar to main.
More complex answer: - threads and main run independently from eachother. You have to wait in your main until you know you can exit main. - your program tends to be unsafe since the vector is accessed by all threads without any synchronisation. Read up on locks, mutexes and semaphores!
Upvotes: 2