瀏覽代碼

feat: ENV的in_run字段改为互斥锁

SongZihuan 3 年之前
父節點
當前提交
8e1cf0848e
共有 3 個文件被更改,包括 16 次插入4 次删除
  1. 2 1
      src/core/__env.h
  2. 7 0
      src/core/env.c
  3. 7 3
      src/core/run.c

+ 2 - 1
src/core/__env.h

@@ -1,6 +1,7 @@
 #ifndef AFUN_ENV_H_
 #define AFUN_ENV_H_
 #include "tool.h"
+#include "pthread.h"
 
 typedef struct af_Core af_Core;
 typedef struct af_Activity af_Activity;
@@ -233,7 +234,7 @@ struct af_Environment {  // 运行环境
     struct af_Activity *activity;
     struct af_TopMsgProcess *process;
     struct af_Guardian *guardian;
-    bool in_run;
+    pthread_mutex_t in_run;
 };
 
 struct af_LiteralRegex {

+ 7 - 0
src/core/env.c

@@ -821,6 +821,11 @@ static af_GuardianList *guardian_Signal(char *type, bool is_guard, void *data, a
 
 af_Environment *makeEnvironment(enum GcRunTime grt) {
     af_Environment *env = calloc(1, sizeof(af_Environment));
+
+    pthread_mutexattr_t attr;
+    pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
+    pthread_mutex_init(&env->in_run, &attr);  // 检测锁
+
     env->esv = makeEnvVarSpace();
     env->core = makeCore(grt, env);
     /* 生成global对象 */
@@ -868,6 +873,8 @@ void freeEnvironment(af_Environment *env) {
     freeEnvVarSpace(env->esv);
     freeAllTopMsgProcess(env->process);
     freeAllGuardian(env->guardian, env);
+
+    pthread_mutex_destroy(&env->in_run);
     freeCore(env);  // core最后释放, 因为Object等需要最后释放
 
     if (!res)

+ 7 - 3
src/core/run.c

@@ -100,8 +100,13 @@ static int checkMacro(af_Message *msg, af_Environment *env) {
  * 3. gc模式
  */
 static bool iterCodeInit(af_Code *code, int mode, af_Environment *env) {
-    if (env == NULL || env->core == NULL || env->activity == NULL || env->core->status == core_exit || env->in_run)
+    if (env == NULL || pthread_mutex_trylock(&env->in_run) != 0)
         return false;
+    if (env->core == NULL || env->activity == NULL || env->core->status == core_exit) {
+        pthread_mutex_unlock(&env->in_run);
+        return false;
+    }
+
     if (env->core->status == core_stop)
         env->core->status = core_normal;
 
@@ -138,7 +143,6 @@ static bool iterCodeInit(af_Code *code, int mode, af_Environment *env) {
             return false;
     }
 
-    env->in_run = true;
     return true;
 }
 
@@ -480,7 +484,7 @@ bool iterCode(af_Code *code, int mode, af_Environment *env){
     }
 
 RETURN:
-    env->in_run = false;
+    pthread_mutex_unlock(&env->in_run);
     return re;
 }