用管道实现线程驱动和通信

一,管道读写规则
当没有数据可读时

O_NONBLOCK disable:read调用阻塞,即进程暂停执行,一直等到有数据来到为止。
O_NONBLOCK enable:read调用返回-1,errno值为EAGAIN。
当管道满的时候

O_NONBLOCK disable: write调用阻塞,直到有进程读走数据
O_NONBLOCK enable:调用返回-1,errno值为EAGAIN

所以我们如果要实现一个简单基于事件机制的线程时,可以让线程阻塞在管道上,线程的唤醒可以通过管道实现。阻塞的时候,线程是会让出CPU的。
二,代码示例如下:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>

void format_time(char *buf, int bufLen)
{
        struct tm local_time;
        struct timeval now;

        gettimeofday(&now, NULL);
        localtime_r(&now.tv_sec, &local_time);

        snprintf(buf, bufLen, "%04d-%02d-%02d %02d:%02d:%02d:%03ld",
        local_time.tm_year + 1900, local_time.tm_mon + 1, local_time.tm_mday,
        local_time.tm_hour, local_time.tm_min, local_time.tm_sec, now.tv_usec / 1000);

}

int g_fds[2];
void * pipe_read(void *param)
{
    printf("creat thread success\n");
    char str[512] = {0};
    format_time(str, 512);
    printf("time:%s\n",str);
    char buf[10] = {0};
    read(g_fds[0],buf,10);
    printf("receive datas = %s\n",buf);
    format_time(str, 512);
    printf("time:%s\n",str);
    return;
}
int main(void)
{
    if(pipe(g_fds) == -1)
    {
        printf("creat pipe error\n");
    }

    pthread_t ptid1;
    pthread_create(&ptid1,NULL,pipe_read,NULL);
    sleep(10);
    write(g_fds[1],"hello",5);
    pthread_join(ptid1,NULL);
    return 0;
}

执行结果:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值