POSIX多线程—异步编程举例

本文通过一个简单的闹钟程序实例,探讨了如何使用POSIX多线程实现异步编程。从同步版本、多进程版本到多线程版本,分析了不同实现方式的特点和优缺点。多线程版本利用pthread_create、pthread_detach等函数,实现线程资源的即时回收,提高了程序并发执行的效率。
摘要由CSDN通过智能技术生成

作者:阿波
链接: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&
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值