centos7 Qt5.9.1 有名信号灯之进程通信

本文介绍了一个基于信号量的通信机制实现案例,通过服务端与客户端的交互演示了信号量的基本用法,包括创建、初始化、获取值及释放等操作。

这个案例里面 信号服务器这边必须先启动。服务端代码:

#include <fcntl.h>           /* For O_* constants */
#include <sys/stat.h>        /* For mode constants */
#include <semaphore.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/mman.h>

#define SEM_NAME "MY_SEM_NAME"

bool bExitThread = false;
sem_t *g_sem;
pthread_t g_thread1;

void* process(void* args)
{
    int* p = (int*)args;
    while(true){
        if(bExitThread){
            break;
        }

        sem_post(g_sem);//通知线程信号量已经置位
        usleep(2000 * 1000);
    }
    delete p;
}
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    g_sem = sem_open(SEM_NAME, O_CREAT | O_EXCL, 0644, 0/*important*/);
    if(errno == EEXIST){//if semaphore exists, delete semaphore from kernel
        sem_unlink(SEM_NAME);//delete semaphore
        g_sem = sem_open(SEM_NAME, O_CREAT | O_EXCL, 0644, 0);//create semaphore
    }

    int val = 0;
    sem_getvalue(g_sem, &val);//test semaphore status

    int *Args1 = new int(1);
    pthread_create(&g_thread1, NULL, process, Args1);//create a thread
}

MainWindow::~MainWindow()
{
    bExitThread = true;
    pthread_join(g_thread1, NULL);//wait thread exit
    sem_close(g_sem);//close semaphore
    sem_unlink(SEM_NAME);//delete semaphore from kernel
    delete ui;
}


客户端代码:

#include <fcntl.h>           /* For O_* constants */
#include <sys/stat.h>        /* For mode constants */
#include <semaphore.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/mman.h>

#define SEM_NAME "MY_SEM_NAME"

bool bExitThread = false;
sem_t *g_sem;
pthread_t g_thread1;
unsigned char *pData = NULL;

void* process(void* args)
{
    int* p = (int*)args;
    while(true){
        if(bExitThread){
            break;
        }
        sem_wait(g_sem);//wait signal
        usleep(1000 * 1000);
    }
    delete p;
}
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    g_sem = sem_open(SEM_NAME, O_CREAT, 0644, 0/*初始化为无信号*/);

    int val = 0;
    sem_getvalue(g_sem, &val);//test semaphore status

    int *Args1 = new int(1);
    pthread_create(&g_thread1, NULL, process, Args1);//create a thread
}

MainWindow::~MainWindow()
{
    bExitThread = true;
    pthread_join(g_thread1, NULL);
    sem_close(g_sem);
    sem_unlink(SEM_NAME);
    delete ui;
}

客户端如果没有信号不会进入usleep函数,如果服务端发送信号了,则信号减1,再次等待

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值