程序目的是保证两个线程交替执行
下载资源
打印结果如下
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();
}