linux下多线程通信(一)「建议收藏」

linux下多线程通信(一)「建议收藏」在linux下进行多线程编程,肯定会涉及到线程通信问题,本文主要分析pipe,即管道在多线之间通信实现。#include<unistd.h>intpipe(intfiledes[2]);返回值:成功,返回0,否则返回-1。参数数组包含pipe使用的两个文件的描述符。fd[0]:读管道,fd[1]:写管道两个线程之间通信简单实现,单向pipe_1.c在这里插入代码片…

大家好,又见面了,我是你们的朋友全栈君。

在linux下进行多线程编程,肯定会涉及到线程通信问题,本文主要分析pipe,即管道在多线之间通信实现。
#include<unistd.h>
int pipe(int filedes[2]);
返回值:成功,返回0,否则返回-1。
参数数组包含pipe使用的两个文件的描述符。fd[0]:读管道,fd[1]:写管道

两个线程之间通信简单实现,单向pipe_1.c
源码地址:https://github.com/jeremy505/multi-thread-communication

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
Thread *m_Threads;
static int threadcount = 1;
void* work_thread(void* argc)
{
  Thread* param = (Thread*) argc;
  printf("childthread_tid=%lu\n", param->tid);
  int contant = 0;
  //sleep(2);
  printf("childthread--read return %d\n",read(param->notifyReceiveFd, &contant, sizeof(int)));
  printf("childthread--read from pipe %d\n", contant);
}

int main(int argc, char** argv)
{
     //在主线程和子线程之间建立管道
    m_Threads = malloc(sizeof(Thread) * threadcount);
    int fds[2];
    if( pipe(fds) )
    {
      perror("create pipe error");
    }
    m_Threads[0].notifyReceiveFd = fds[0];
    pthread_create(&m_Threads[0].tid, NULL,  work_thread, (void*)&m_Threads[0]);
    printf("mainthread_tid=%lu\n", m_Threads[0].tid);
    int contant = 1;
    // sleep(2);
    printf("mainthread--write %d to pipe\n", contant);
    printf("mainthread--write return %d\n",write(fds[1], &contant, sizeof(int)));
    pthread_join(m_Threads[0].tid, NULL);
    close(fds[0]);
    close(fds[1]);
    return 0;
}

以上只是单向通信,即主线程向子线程写int型值1,子线程读到int型值1.
输出见下:
在这里插入图片描述
在这里插入图片描述
可见,输出与设想的一致,只是此时通信只是单向,如果要实现双向,最简单的办法就是再创建一组pipe,实现pipe_1_d.c如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
typedef struct __Thread
{
  pthread_t tid;    //线程的ID
  int notifyReceiveFd;  //管道的接收端
  int notifySendFd;   //管道的发送端
}Thread;

Thread *m_Threads;
static int threadcount = 1;
void* work_thread(void* argc)
{
  Thread* param = (Thread*) argc;
  printf("childthread_tid=%lu\n", param->tid);
  int contant = 0;
  //sleep(2);
  printf("childthread--read return %d\n",read(param->notifyReceiveFd, &contant, sizeof(int)));
  printf("childthread--read from pipe %d\n", contant);
  contant = 2;
  printf("childthread--write %d to pipe\n", contant);
  printf("childthread--write return %d\n",write(param->notifySendFd, &contant, sizeof(int)));
}

int main(int argc, char** argv)
{
     //在主线程和子线程之间建立管道
    m_Threads = malloc(sizeof(Thread) * threadcount);
    int fds[2];
    if( pipe(fds) )
    {
      perror("create pipe fds error");
    }
    int fds_1[2];
    if( pipe(fds_1) )
    {
      perror("create pipe fds_1 error");
    }
    m_Threads[0].notifyReceiveFd = fds[0];
    m_Threads[0].notifySendFd = fds_1[1];
     pthread_create(&m_Threads[0].tid, NULL,
                   work_thread, (void*)&m_Threads[0]);
    printf("mainthread_tid=%lu\n", m_Threads[0].tid);
    int contant = 1;
    // sleep(2);
    printf("mainthread--write %d to pipe\n", contant);
    printf("mainthread--write return %d\n",write(fds[1], &contant, sizeof(int)));
    printf("mainthread--read return %d\n",read(fds_1[0], &contant, sizeof(int)));
    printf("mainthread--read from pipe %d\n", contant);
    pthread_join(m_Threads[0].tid, NULL);
    close(fds[0]);
    close(fds[1]);
    close(fds_1[0]);
    close(fds_1[1]);
    }

另外创建一组pipe,主线读,子线程写。主线程先写1,然后阻塞等待子线程网管道中写值,子线程通过管道读到1之后往管道写2,此时管道有数据,主线程读取值2,输出如下:
在这里插入图片描述

以上只是简单的通过pipe线程之间进行同行,注意到读写都是阻塞的。如果不希望线程使用阻塞方式,一般会设置管道文件描述符为非阻塞,然后借助epoll或者select监听管道文件描述符读写事件。
线程之间通过pipe通信也可以应用到进程之间,在使用fork之后,管道描述符被拷贝了一份,所以父子进程必须关闭其中之一,假设父进程关闭读[close(fd[0])],子进程就要关闭写[close(fd[1])],,实现单向通信,反过来也是一样.
进程之间的通信,推荐一种方式使用共享内存,共享内存区是最快的IPC形式,此种方式也可在两个完全独立的程序之间进行数据传递,后续再详细介绍。
当然,进程以及线程之间的通信不止以上方法,还有使用socket,eventfd等。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/150749.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • spring拦截器和过滤器有什么区别_拦截器和过滤器的区别面试

    spring拦截器和过滤器有什么区别_拦截器和过滤器的区别面试简介这几天在回顾Spring的AOP时,对过滤器,拦截器,AOP的关系有点好奇,故记录做以备份。在实现一些公共逻辑的时候,很多功能通过过滤器,拦截器,AOP都能实现,但是不同的方式有不同的效率。具体有什么区别,看下文描述。前后端交互基本逻辑过滤器过滤器拦截的是URLSpring中自定义过滤器(Filter)一般只有一个方法,返回值是void,当请求到达web容器时,会探测当…

    2022年8月23日
    7
  • java ORA-01008: 并非所有变量都已绑定避坑

    java ORA-01008: 并非所有变量都已绑定避坑//数据库增加数据的函数 publicbooleanadd(Creditc){ Stringsql=”insertintocredit(id,name,pwd,Money)” +”values(?,?,?,?)”; //要插入的对象中的数据拿到object数组中 Objecto[]={c.getId(),c.getName(),c.getPwd()…

    2025年9月25日
    3
  • sparksql报错

    sparksql报错Exceptionint main org apache spark sql catalyst errors package TreeNodeExce execute tree Exchangehash subject 6 200 HashAggregat keys subject 6 name 7 functions count 1 output subject 6 name 7 c 12L E

    2025年8月30日
    2
  • JAVA的垃圾回收机制_java的内存回收机制

    JAVA的垃圾回收机制_java的内存回收机制一:垃圾回收机制的意义java语言中一个显著的特点就是引入了java回收机制,是c++程序员最头疼的内存管理的问题迎刃而解,它使得java程序员在编写程序的时候不在考虑内存管理。由于有个垃圾回收机制,java中的额对象不在有“作用域”的概念,只有对象的引用才有“作用域”。垃圾回收可以有效的防止内存泄露,有效的使用空闲的内存;内存泄露:指该内存空间使用完毕后未回收,在不涉及复杂数据结构的一般…

    2022年10月10日
    2
  • ASPCMS_net开源项目

    ASPCMS_net开源项目1.We7CMS【做的还不错,需要保留版权】We7CMS是由西部动力开发的一款充分发掘互联网Web2.0(如博客、RSS等)的信息组织优势,将其理念利用到政府企事业网站的构建、组织、管理中的网站建设和管理方面的产品。系统目标:叫创建网站变成一种简单的艺术创作,简单如创建博客。系统特点简单至上;“一看就会”是我们的创作理念,如果在哪里您看了不会用,请您告诉我们。潜力无限;来自

    2022年9月30日
    2
  • python分类模型_nlp模型评估指标

    python分类模型_nlp模型评估指标不知道你是否已经看完了我之前讲过的有关机器学习的文章,如果没看过也没关系,因为本篇文章介绍的内容适用于所有分类模型(包括神经网络),主要就是介绍分类模型的评估指标。另外,在前面我还会提一下数据不平衡的问题该如何处理。总之本篇文章实用性极强!…

    2022年10月6日
    4

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号