you lock the variable in the outer scope, and that lock is never released -- not an improvement
Provided that the OP only ever wants to do exactly what his OP code attempts to do -- which is nothing useful -- then ikegami's code has a fair chance of running on platforms that support condition variables natively.
But, even on those platforms, if, as seems almost certain, the OPs code is just a cut-down placeholder for his real application, and there is more (almost anything more) going on inside those while loops (and there has to be, because in their current form they do nothing useful), then every single extra clock-cycle spent doing that 'more' before looping back to the cond_wait() call, is time that other threads ought to be able to make forward progress, but can't because ikegami's code doesn't release the cond-var; except for the briefest of windows when it calls cond_wait().
So, for instance if the user adds a simple call to the regex engine that runs for (say) 0.1 seconds; then the ratio of the cond_wait() release (say) 0.0001 seconds to that trivial amount of useful processing is 1000:1. And that means that all the other threads that are blocking and syncing on that cond_var can AT MOST expect to make forward progress for no more than 1/1000 of a second in every second. And if there are two other threads, then they can AT MOST make progress for on 1/1000 of a second in every two seconds, and so on. (And if they themselves are also doing other stuff in their while loops, then the odds that one thread will actually be waiting, ready to run, in the minusculey brief period when another thread releases the cond_var; becomes vanishingly small.
The upshot is, that in addition to not working on windows, his code provides a disastrous example of using cond_vars, because it will only ever work (on some platforms) for entirely trivial, do nothing examples; and will break every time, (everywhere), for any program that does real work, and attempts to use the pattern of usage he demonstrates.
The difference between playing and knowing. Not that it will undo the entirely wrong upvotes by those who vote based upon hero worship rather than content.
Not that the votes mean anything; except that when people coming looking for solutions, the "highest first" sorting of nodes will likely push his node up, and so seekers will get lumped with his example, and when it breaks for their real world usage, they'll be left floundering trying fix what they will perceive as bugs they introduced; when in fact those bugs are inherent in the example code they downloaded.
His code is like a latent virus, biding its time before causing the epidemic. (But what does he care; he's got his up-votes and bolstered his rep., which is all he cares about.)
In reply to Re^4: Threads sharing global variable
by BrowserUk
in thread Threads sharing global variable
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |