Global variables, re-entry code, and thread safety

I am trying to decide whether to perform certain operations as macros or as functions.

Let's say, as an example, I have the following code in the header file:

extern int x_GLOB;
extern int y_GLOB;

#define min(x,y) ((x_GLOB = (x)) < (y_GLOB = (y))? x_GLOB : y_GLOB)

the goal is for each single argument to be evaluated only once ( min(x++,y++)it will not cause any problems here).

The question is: do two global variables have any problems in terms of re-entering code or thread safety?

I would say no, but I'm not sure.

What about:

#define min(x,y) ((x_GLOB = (x)), \
                  (y_GLOB = (y)), \
                  ((x_GLOB < y_GLOB) ? x_GLOB : y_GLOB)

will it be another case?

Please note that the question is not "generally", but because these global variables are used only inside this macro and to evaluate a single expression.

, , , :

  • , , "" ( )

  • "" , , "" , , , (, min (min (1,2), min (3,1)).

, - - , , , - , .

+3
6

, , .

:

int a = min(min(1, 2), min(3, 4));

?

  • min (1, 2) x_GLOB ( ):
    • x_GLOB = 1
    • y_GLOB = 2
    • min, 1, x_GLOB ( )
  • min (3, 4) y_GLOB ( ):
    • x_GLOB = 3 (uh-oh, 1 )
    • y_GLOB = 4
    • min, 3, y_GLOB ( )
  • min (a, b), a - min (1, 2) b - min (3, 4)
    • min x_GLOB ( 3) y_GLOB ( 3)
    • 3

- ?

+1

min - .

  • , min ( min, C)
  • min
  • gcc-, .

- , , , - .

1:

#define MIN(x, y) ((x) < (y) ? (x) : (y))

2:

int min(int x, int y) { return x < y ? x : y; }

, , min .

3:

#define min(x, y) ({ \
    typeof(x) x__ = (x); \
    typeof(y) y__ = (y); \
    x__ < y__ ? x__ : y__; \
})
+4

. , .

, !

+2

, , , ( ) .

, , (, ..) " ".

Wikipedia reentrant

+1

-. , , A min (1,2) threadB min (3,4). , A , .

x_GLOB 1, y_GLOB 2.

, threadB :

x_GLOB 3, y_GLOB - 4.

, threadA . x_GLOB (3) (1).

, - " " , threadA 3, x_GLOB . , . , , - .

. , :

#define STATIC_INLINE static

STATIC_INLINE int min_func(int x, int y) { return x < y ? x : y; }

#define min(a,b) min_func((a),(b))

, - , , , - , , , STATIC_INLINE - ( static inline C99, static __inline Microsoft - ), , , min -. ( " ?" ) -, .

+1

.

, ( " ++" ).

0

Source: https://habr.com/ru/post/1727943/


All Articles