The appearance of SWOLE 4 coprocessor has changed PHP from serial mode to concurrent mode. There are many PHP’sC/C++
Extension failed to consider concurrency during development,ReentryProblems, resulting in unable to inSwoole
Used in coordination. This article will explain in detail how to write coordination concurrent securityC/C++
Code.
Reentry
Sample code:
int t;
void test1(int *x, int *y) {
t = *x;
*x = *y;
//there may be synergetic switching in //fun1 function
fun1();
//Error Code
*y = t;
}
-
t
Is a global variable orstatic
Static variable - In the coordination process
A
Called intest1
Function, using global variablest
- When called within a function
fun1()
If there is a synergetic switch in this function, then if there is another synergetic switchB
Also implementedtest1
Function, thent
The value of may be modified - coroutine
B
When suspended, return to the coordination processA
At this time*y = t
, will get an incorrect value
Reference stack memory
This is also a serious risk point. coroutine1
Sending the pointer of its own stack memory to another coprocessor2
, association1
When exiting, the synergetic stack memory will be released. coroutine2
The life cycle of is longer than that of1
, continue to read and write this memory, will result insegment fault
.
Examples:
void co1() {
char buf[2048];
//Here, a new synergetic process is started. buf is the memory on the synergetic process 1 stack
co2(buf);
//when coprocessor 1 exits, stack memory will be released
}
void co2(char *buf) {
for(int i=0; i<2048; i++) {
Coroutine::sleep(1);
//buf memory may have been released here
buf[i] = 1;
}
}
Coordination safety code
In order to ensure safety, inSwoole4
In synergetic programming:
- Do not use
static
Variables and global variables, adhere to only local variables - If global variables must be accessed, it must be guaranteed to be used only for calculation logic and there must be no
IO
OrSleep
Such as cause coordinated process switching operation - Do not call any other non-reentrant functions
- Do not reference memory on stack