Qt 多线程同步(信号量实现)

本文介绍了一种使用信号量实现两个线程之间的交替执行机制。通过定义信号量和全局变量,确保了两个线程能够按照预设顺序执行,并展示了具体的实现代码及运行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

程序目的是保证两个线程交替执行

下载资源
打印结果如下
Mythread————————-0
Mythread1————————1
Mythread—————————2
Mythread1————————–3

gdata.h

#ifndef GDATA_H
#define GDATA_H
#include <mutex>
#include <iostream>
#include <QSemaphore>

class Gdata
{
public:
    Gdata();
    QSemaphore * sem1;
    QSemaphore * sem2;
    int gNum;
};

#endif // GDATA_H

gdata.cpp

#include "gdata.h"
Gdata::Gdata()
{
    sem1 = new QSemaphore(0);
    sem2 = new QSemaphore(0);
    gNum = 0;
}

mythread.h

#ifndef MYTHREAD_H
#define MYTHREAD_H
#include "gdata.h"
#include <QThread>
class Mythread : public QThread
{
public:
    Mythread(Gdata * pData);
    void star();
    void run();
    Gdata * pData;
};

#endif // MYTHREAD_H

mythread.cpp

#include "mythread.h"
#include <QDebug>
Mythread::Mythread(Gdata *pData)
{
    this->pData = pData;
}

void Mythread::star()
{
     QThread::start();
}

void Mythread::run()
{
    while(1)
    {
        qDebug() << "Mythread------------------------%d " << pData->gNum ++ ;
        pData->sem1->release(); // +1
        msleep(200);
        pData->sem2->acquire(); // -1
    }
}

mythread1.h

#ifndef MYTHREAD1_H
#define MYTHREAD1_H
#include <QThread>
#include "gdata.h"
class Mythread1 : public QThread
{
public:
    Mythread1(Gdata * pData);

    void run();
    void star();
    Gdata * pData;
};

#endif // MYTHREAD1_H

mythread1.cpp

#include "mythread1.h"
#include <QDebug>
Mythread1::Mythread1(Gdata *pData)
{
    this->pData = pData;
}

void Mythread1::run()
{
    while(1)
    {
        pData->sem1->acquire(); // -1
        qDebug() << "Mythread1................." << pData->gNum ++;
        msleep(30);
        pData->sem2->release(); // +1
    }
}

void Mythread1::star()
{
    QThread::start();
}

main.cpp

#include <QCoreApplication>
#include "mythread.h"
#include "mythread1.h"
#include "gdata.h"

int main(int argc, char *argv[])
{

    Gdata * pGdata = new Gdata();
    Mythread t(pGdata);
    Mythread1 t1(pGdata);

    t.star();
    t1.star();
    QCoreApplication a(argc, argv);

    return a.exec();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值