0x00 描述
在计算机内存中同时存放几道相互独立的程序,它们在管理程序控制之下,相互穿插的运行。多道程序设计必须有硬件基础作为保证。
时钟中断即为多道程序设计模型的理论基础。 并发时,任意进程在执行期间都不希望放弃cpu。因此系统需要一种强制让进程让出cpu资源的手段。时钟中断有硬件基础作为保障,对进程而言不可抗拒。操作系统中的中断处理函数,来负责调度程序执行。
在多道程序设计模型中,多个进程轮流使用CPU(分时复用CPU资源)。而当下常见CPU为纳秒级,1秒可以执行大约10亿条指令。由于人眼的反应速度是毫秒级,所以看似同时在运行。
1s = 1000ms,1ms = 1000us, 1us = 1000ns 1000000000
实质上,并发是宏观并行,微观串行! -----推动了计算机蓬勃发展,将人类引入了多媒体时代。
0x01 代码实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
//模拟日记记录
#define log_func(msg){ \
do{ \
printf("%s \n", msg); \
}while(0); \
}
int main(int argc, char* argv[])
{
int tty_fd = open("/dev/tty", O_NONBLOCK | O_RDONLY, 0);
if(-1 == tty_fd)
{
log_func("没有获取终端句柄!");
exit(1);
}
/*用for循环模拟超时机制*/
int time_out_nums = 10;
int i = 0;
int input_string_len = 0;
char buf[1024];
memset(buf, 0, sizeof(buf));
for(;
i < time_out_nums;
++i)
{
input_string_len = read(tty_fd, buf, sizeof(buf));
if(input_string_len > 0)
{
goto END;
}
printf("waiting input... ....\n");
sleep(1);
}
//提示已经超时
END:
if(i == time_out_nums)
{
printf("已经超时!");
}else{
write(tty_fd, buf, sizeof(input_string_len));
}
return 0;
}