You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@celix.apache.org by Bjoern Petri <bj...@sundevil.de> on 2015/05/20 08:02:47 UTC
replace booleans as sync primitives
Hi everyone,
For several of our bundles we use the same approach to control
additional threads within
a bundle:
A boolean variable is used to indicate whether the thread is supposed to
run. The
according thread function regularly checks whether this variable is set
(e.g.
threadIsRunning == true) and returns when set to false. When stopping
the bundle
we usually set this variable to false followed by a pthread_join.
This approach seems to have some flaws:
- Usually the boolean variables are not declared volatile. This should
be done to
guarantee that the write has actually happened before another read. In
case this
is not done, the thread might still be executed although the global
variable
indicates to not do so. This might lead to a problem when we invalidate
data after
setting the global variable (and before doing a pthread_join).
- Even when having the boolean variables declared volatile, the compiler
may re-order
the code as a result of compiler optimizations. So, data might be
invalidated before
the boolean variable is set to false.
That's why it may be preferable to replace the sync primitive for
threading with an
appropriate approach.
While this issue has already been commented on JIRA, it might be useful
to gather some
more opinions on this issue and how it can be solved best. Any comments
are welcome.
Regards,
Bjoern
See also:
https://issues.apache.org/jira/browse/CELIX-233
http://stackoverflow.com/a/2485177/4354534
https://www.securecoding.cert.org/confluence/display/c/CON02-C.+Do+not+use+volatile+as+a+synchronization+primitive
http://www.drdobbs.com/cpp/volatile-the-multithreaded-programmers-b/184403766