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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Linux安装vim编辑器_linux系统安装jdk教程

    Linux安装vim编辑器_linux系统安装jdk教程1、yum下载vimyum-yinstallvim*2、安装完之后开始配置vimvim/etc/vimrc3、打开文件后,添加如下代码setnu”设置显示行号setshowmode”设置在命令行界面最下面显示当前模式等setruler”在右下角显示光标所在的行数等信息setautoindent”设置每次单击Enter键后,光标移动到下一行时与上一行的起始字符对齐syntaxon”即设置语法检测,当编辑C或者Shell脚本时,

    2025年8月1日
    3
  • sprintf函数的用法linux,sprintf函数用法解析

    sprintf函数的用法linux,sprintf函数用法解析shortsi=-1;sprintf(s,”%04X”,si);产生“FFFFFFFF”,怎么回事?因为spritnf是个变参函数,除了前面两个参数之外,后面的参数都不是类型安全的,函数更没有办法仅仅通过一个“%X”就能得知当初函数调用前参数压栈时被压进来的到底是个4字节的整数还是个2字节的短整数,所以采取了统一4字节的处理方式,导致参数压栈时做了符号扩展,扩展成了32位的整数…

    2022年6月16日
    43
  • R-L模型算法的优缺点_风筝模型公式

    R-L模型算法的优缺点_风筝模型公式介绍Logistic回归算法,名字虽带有回归,但其实是一个分类模型。输出Y=1的对数几率是由输入x的线性函数表示的模型,直接对分类的可能性进行建模,并不是直接对分类的结果(0或者1)进行建模:假设一个样本属于正样本的概率为p,则:LR模型是在线性回归的基础上,把特征进行线性组合,再把组合的结果通过一层sigmoid函数映射成结果是1或是0的概率。逻辑斯蒂回归模型的特点:…

    2022年10月13日
    5
  • Fiddler+夜神模拟器进行APP抓包

    Fiddler+夜神模拟器进行APP抓包Fiddler+夜神模拟器进行APP抓包作者:霞落满天需求:对公司APP进行抓包获取详细的接口信息,这是现在开发必备的。工具:Fiddler抓包,夜神模拟器模拟手机安装APP1.下载Fiddlerhttps://www.telerik.com/download/fiddlerFiddler正是在这里帮助您记录计算机和Internet之间传递的所有HTTP和HTTPS通信…

    2022年5月7日
    104
  • JAVA贪吃蛇小游戏源代码系列

    JAVA贪吃蛇小游戏源代码系列Java贪吃蛇小游戏元源代码

    2022年5月9日
    128
  • 神经网络优化(初始化权重)

    神经网络优化(初始化权重)使隐藏层饱和了,跟之前我们说的输出层饱和问题相似,对于输出层,我们用改进的cost函数,比如cross-entropy,但是对于隐藏层,我们无法通过cost函数来改进更好的方法来初始化权重?因为传统的初始化权重问题是用标准正态分布(均值为0,方差为1)随机初始化的,这其实是存在不合理的部分。标准正态分布:可以看出真实数据的

    2022年9月27日
    6

发表回复

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

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