C语言实现自定义函数无限循环运行不阻塞主函数执行的问题
问题根源
你的单线程程序中,timer函数内部的无限循环会完全阻塞后续库存管理逻辑的执行,程序卡在时间刷新环节永远不会进入用户交互分支。要同时满足实时时间刷新和业务逻辑运行,推荐使用多线程异步方案实现。
修复后完整实现(Windows平台)
该方案将时间刷新逻辑放到独立线程运行,和主业务逻辑完全并行,无需调整原有库存管理的代码流程,时间全程实时刷新无干扰。
#include <stdio.h> #include <time.h> #include <windows.h> // 时间刷新线程函数 DWORD WINAPI timer(LPVOID lpParam) { char cur_time[128]; for(;;) { time_t t = time(NULL); struct tm* ptm = localtime(&t); strftime(cur_time, 128, "%d-%b-%Y %H:%M:%S", ptm); // \r回到行首实现同一行覆盖刷新,fflush强制清空缓冲区确保立即输出 printf("\r Current date and time: %s", cur_time); fflush(stdout); Sleep(1000); // 每秒刷新一次,避免占用过多CPU资源 } return 0; } int main() { // 先启动时间刷新线程,后续主逻辑完全不受影响 CreateThread(NULL, 0, timer, NULL, 0, NULL); printf("\n*-----STORE STOCK MANAGER-----*\n"); int option; l1: // 打印业务内容前先输出换行,避免覆盖顶部的时间显示行 printf("\n"); printf("press \n1 for Manager \n2 for Staff\n"); printf("Manager or staff:"); scanf("%d",&option); switch(option) { case 1: printf("you're a Manager"); break; case 2: printf("You're a staff"); break; default: printf("Invalid Input! Please Choose the correct option\n\a"); } Sleep(3000); system("cls"); goto l1; return 0; }
Linux平台适配修改点
如果运行在Linux环境,只需调整多线程相关代码即可:
- 引入头文件
<pthread.h>和<unistd.h> - 时间线程函数改为:
void* timer(void* arg) { char cur_time[128]; for(;;) { time_t t = time(NULL); struct tm* ptm = localtime(&t); strftime(cur_time, 128, "%d-%b-%Y %H:%M:%S", ptm); printf("\r Current date and time: %s", cur_time); fflush(stdout); sleep(1); } } - main函数中启动线程的代码替换为:
pthread_t tid; pthread_create(&tid, NULL, timer, NULL); - 编译时添加线程库参数:
gcc 你的代码文件名.c -o stock_manager -lpthread
内容的提问来源于stack exchange,提问作者MrWhoseTheNoob
相关产品推荐
相关产品推荐

