But if i do that the threads never execute as 'main' terminates and all the threads die. Any reason why you think it might help?
I found a possible solution to the problem, since the threads would sleep in 'Display' and by the time they wake up, main exits hence 'i' doesn't exist anymore and when i try to print the value it crashes. Actually i executed it once without the 'sleep' and it went through fine. Though i think it might still crash some other time when main exits before any of the threads is left incomplete.
It doesn't matter that 'i' doesn't exist when main() ends and the thread is using it, simply because when main() ends the whole program shuts down, including the threads.
Last edited by unbeatable0; Dec 18th, 2008 at 8:23 am. Reason: Have written 'than' instead of 'that'
It doesn't matter than 'i' doesn't exist when main() ends and the thread is using it, simply because when main() ends the whole program shuts down, including the threads.
The threads wont shut down because I'm using 'ExitThread', if I'm not wrong its the equivalent of pthread_exit for Unix.
> Any clues why?
Because you passed a POINTER to i.
The main() thread exits, the i variable goes out of scope and another thread is looking down the barrel of a segfault.
> also any general tips for writing good multi-threaded code are welcome.
Well the first step is to make sure that whatever parameter you pass has a lifetime which exceeds the thread creator.
Using dynamic memory, and then making the thread the owner of that memory is one way to achieve this.
This also solves the other problem of helping to ensure that only one thread has access to the memory passed into it.
Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.
This thread is more than three months old
No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.