作者:阿波
链接:http://blog.csdn.net/livelylittlefish/article/details/7952884
(整半年没有更新,发几篇以前的读书笔记。)
Content
0. 序
1. 基本的同步版本
2. 多进程版本
3. 多线程版本
4. 小结
0. 序
本节通过一个简单的闹钟实例演示异步编程方法。
该程序循环接受用户输入信息,直到出错或者输入完毕。用户输入的每行信息有两部分:闹钟等待的时间(秒)和闹钟时间到达时显示的文本信息。
1. 基本的同步版本
代码如下。
/*
* alarm.c
*
* Simple synchronous alarm program. This is used as a
* reference for progressive examples of asynchronous
* alarm programs.
*/
#include "errors.h"
int main (int argc, char **argv)
{
int seconds;
char line[128];
char message[64];
while (1)
{
printf("Alarm> ");
if (fgets(line, sizeof(line), stdin) == NULL)
exit(0);
if (strlen(line) <= 1)
continue;
/**
Parse input line into seconds (%d) and a message (%64[^\n]),
consisting of up to 64 characters separated from the seconds
by whitespace.
*/
if (sscanf(line, "%d %64[^\n]", &seconds, message) < 2)
{
fprintf(stderr, "Bad command\n");
}
else
{
sleep(seconds);
printf("(%d) %s\n", seconds, message);
}
}
}
特点:同步实现异步,闹钟请求后,程序睡眠等待闹钟时间到;
问题:用同步方式来实现异步,致一次只能处理一个闹钟请求;即程序睡眠时间到后才能进行下一次闹钟请求;
运行结果。
# ./alarm
Alarm> 5
Bad command
Alarm> 5 this is a test with 5 seconds
(5) this is a test with 5 seconds //等待5秒并打印该消息
Alarm> 10 the seconds with 10 seconds
(10) the seconds with 10 seconds //等待10秒并打印该消息
Alarm&