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

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

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

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

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

#include 
#include 
#include 
#include 
#include 
#include 
#include 

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;
}

执行结果:
用管道实现线程驱动和通信_第1张图片

你可能感兴趣的:(进程线程同步与通信,操作系统,线程,管道,pipe)