c++ - assignment in pthreads application -
i have linux multithread application in c++. in application in class app
offer variable status
:
class app { ... typedef enum { asstop=0, asstart, asrestart, aswork, asclose } tappstatus; tappstatus status; ... }
all threads check status
calling getstatus()
function.
inline tappstatus app::getstatus(){ return status };
other functions of application can assign different values status
variable calling setstatus()
function , not use mutexes.
void app::setstatus( tappstatus astatus ){ status=astatus };
edit: threads use status
in switch
operator:
switch ( app::getstatus() ){ case asstop: ... case asstart: ... };
- is assignment in case, atomic operation?
- is correct code?
thanks.
there no portable way implement synchronized variables in c99 or c++03 , pthread library not provide 1 either. can:
- use c++0x
<atomic>
header (or c1x<stdatomic.h>
). gcc support c++ if given-std=c++0x
or-std=gnu++0x
option since version 4.4. - use linux-specific
<linux/atomic.h>
(this implementation used kernel, should usable userland well). - use gcc-specific
__sync_*
builtin functions. - use other library provides atomic operations glib.
- use locks, that's orders of magnitude slower compared fast operation itself.
note: martinho pointed out, while called "atomic", store , load it's not atomic property (operation cannot interrupted , load sees or not see whole store, true of 32-bit stores , loads) ordering property (if store , b, nobody may new value of b , old value of a) hard necessary in case.
Comments
Post a Comment