16,203
社区成员
发帖
与我相关
我的任务
分享
#include <QCoreApplication>
#include <QEventLoop>
#include <QSemaphore>
#include <QTimer>
#include <QThread>
#include <QDebug>
class MyImage : public QThread
{
Q_OBJECT
public:
explicit MyImage(QSemaphore *sem, int index = 0) : sem(sem), index(index){}
~MyImage() { this->exit(); this->wait(); }
public slots :
void startImageCreate()
{
sem->acquire(index);
qDebug() << "index:" << index;
sem->release(index+1);
this->exit();
}
private:
QSemaphore *sem;
int index;
};
class Process1_9
{
public:
Process1_9() : sem(1){}
~Process1_9(){}
void process()
{
QEventLoop loop;
QVector<MyImage*> threads;
for (int k = 1; k <= 9; k++)
{
MyImage *myImage = new MyImage(&sem, k);
if (k == 9)
{
QObject::connect(myImage, SIGNAL(finished()), &loop, SLOT(quit()));
}
threads.append(myImage);
myImage->start();
myImage->moveToThread(myImage);
QTimer::singleShot(0, myImage, SLOT(startImageCreate()));
}
loop.exec();
qDeleteAll(threads);
}
private:
QSemaphore sem;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
for (int i = 0; i < 3; ++i)
{
Process1_9 p;
p.process();
qDebug() << "===times:" << i + 1;
QEventLoop loop;
QTimer::singleShot(1000, &loop, SLOT(quit()));
loop.exec();
}
return a.exec();
}
#include "main.moc"
就是把1-9的执行再封装一下呀. 方式很多,我随便写的.你看着修改吧.
#include <QCoreApplication>
#include <QSemaphore>
#include <QTimer>
#include <QThread>
#include <QDebug>
class MyImage : public QObject
{
Q_OBJECT
public:
explicit MyImage(int index = 0);
public slots :
void startImageCreate();
private:
int index;
};
static QSemaphore sem(1);
MyImage::MyImage(int No) :QObject()
{
index = No ;
}
void MyImage::startImageCreate()
{
sem.acquire(index); //获取资源,
qDebug() << "index:" << index;
sem.release(index+1);//释放多一个的资源,刚好可以,让下一个acquire获取成功.
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QVector<QThread*> threads;
for (int k = 1; k <= 9; k++) //从一开始.到9结束
{
QThread *imageThread = new QThread;
MyImage *myImage = new MyImage(k);
imageThread->start(); //启动线程
myImage->moveToThread(imageThread);
threads.append(imageThread);
//用QTimer来触发槽,和连接一个信号再发出信号一个效果,都是Qt::QueuedConnection效果.
QTimer::singleShot(0, myImage, SLOT(startImageCreate()));
}
return a.exec();
}
#include "main.moc"