فهرست منبع

优化修改sw_signal_wait()函数

niujiuru 1 ماه پیش
والد
کامیت
aa1b9acd04
1فایلهای تغییر یافته به همراه17 افزوده شده و 3 حذف شده
  1. 17 3
      swapi/swsignal.c

+ 17 - 3
swapi/swsignal.c

@@ -5,8 +5,8 @@
  * NOTE: 主要用于状态通知
  * HISTORY:
  * 1, [2010-12-17] created by NiuJiuRu
- * 2, [2025-11-24] 替换"gettimeofday()"为"clock_gettime()", 前者会依赖系统
- *                 时间, 后者依赖单调递增时钟, 避免了系统时间变化带来的影响
+ * 2, [2025-11-24] 优化修改"sw_signal_wait()"函数, 使其不依赖系统时间,实现
+ *                 超时等待
  ***********************************************************************/
 #include "swapi.h"
 #include "swmem.h"
@@ -50,8 +50,10 @@ wait_p1:
 	}
 	else
 	{
+	if(0)
+  { // 依赖系统时间的超时等待, 内核唤醒
 		struct timespec ts, now;
-		clock_gettime(CLOCK_MONOTONIC, &now);
+		clock_gettime(CLOCK_REALTIME, &now);
 		ts.tv_sec = now.tv_sec + timeout/1000;
 		ts.tv_nsec = now.tv_nsec + (timeout%1000)*1000*1000;
 		if(ts.tv_nsec >= (1000*1000*1000))
@@ -64,6 +66,18 @@ wait_p2:
 		if(ret < 0 && errno == EINTR) goto wait_p2;
 		else return ret;
 	}
+	else
+	{ // 无视系统时间的超时等待, 轮询检查
+		struct timespec ts = {0, 1000*1000}; // 1ms
+		while((ret = sem_trywait(sem)) < 0 && errno == EAGAIN)
+		{
+		  if(timeout <= 0) return -1;
+		  nanosleep(&ts, NULL);
+		  timeout -= 1;
+		}
+		return ret;
+	}
+	}
 }
 
 /* 点亮信号量 */