| Ramses12 (89) | |||
|
Hi. I've been experimenting with basic threading, trying to create a thread running a loop, and being breakable by cin action. Here's my code:
By my calculations, it should create the separate thread running Loop(), wait for user input, and when the user presses enter, break the loop (aka. display the "Broken!" message box). However, nothing seems to happen. The more bizarre part is that if I add something like: cout<<"."; inside the while(1) loop, it suddenly and magically starts working perfectly: it couts . all over the screen, but when I press enter, it displays the "Broken!" message, which is what I want. Now why would that happen? How is anything related to what is executed inside the threaded function? Thanks in advance. | |||
|
|
|||
| andywestken (1950) | |
|
Are you building the release target? If so, try making BreakIt volatile. volatile int BreakIt(0);Andy | |
|
|
|
| Ramses12 (89) | |||
|
Seems to be working. Thank you. What was I doing wrong? I know the "volatile" prevents optimization, so perhaps somehow the loop was being modified (erasing the if(BreakIt)break; line since the compiler assumed BreakIt will never change state perhaps?), but why did the cout call make things work?
or need I "volatilize" something in here too? [Edit] This exact code is doing its job. Going to debug what the problem is. [Edit] It's looking good now. No idea how that error showed up. | |||
|
Last edited on
|
|||
| andywestken (1950) | |||
|
Yes, it's the optization. I guess that the optimization wasn't worth doing when the cost of the cout call had to be met. But as the wait loop you're using is something that should never occur in real code, this particular problem is just a curiousity. Spinning an empty loop is potentially very costly in terms of CPU, so you would use a wait function in practice. Using a class for the thread is better. This code is just for illustrative purposes.
Andy | |||
|
Last edited on
|
|||
| Ramses12 (89) | |
|
I see. Compilers are complicated things :D It's hard to understand how they "think" everything... Thank you for the time. I'll now mark this as solved. | |
|
|
|