QT之线程池
run.h
#ifndef RUN_H #define RUN_H #include <QObject> #include <QRunnable> #include <string> #include <iostream> struct MyString { std::string valueStr; //定义结构体 }; class Run : public QObject , public QRunnable { Q_OBJECT public: Run() = default; Run(const MyString& myString); protected: ~Run() = default; void run(); //重写run函数 signals: public slots: private: MyString myString; }; #endif // RUN_H
run.cpp
#include "run.h" #include <QThread> #include <QDebug> Run::Run(const MyString &myString) { this->myString = myString; //this->setAutoDelete(true);//默认就是true ,自动回收 } void Run::run() { //std::cout << "value:" << this->myString.valueStr <<";调用线程ID为:" << QThread::currentThread() << std::endl; qDebug() << "value:" << QString::fromStdString(myString.valueStr) << "thread:" << QThread::currentThreadId(); QThread::msleep(100); }
main.cpp
#include <QCoreApplication> #include "run.h" #include <queue> #include <mutex> #include <QThreadPool> #include <thread> using namespace std; queue<MyString> myList; mutex myMutex; volatile bool addThreadIsEnd = false; // 加入生产者是否结束 void makeListThread(); int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); cout << "begin main" << endl; thread addThread(makeListThread); // 加入生产者 addThread.detach(); cout << "begin addThread" << endl; QThreadPool tp; tp.setMaxThreadCount(20); cout << "begin threadPool" << endl; while(true) { if(!myList.empty()) { MyString tempMyString = myList.front(); //取出队列第一个元素 tp.start(new Run(tempMyString)); // 这里new了一个没有指针指向的Runnable对象,在哪里回收的呢?Run.setAutoDelete(true)自动回收 myMutex.lock(); // 加锁 myList.pop(); myMutex.unlock(); // 解锁 } else { if(addThreadIsEnd) { break; } else { QThread::msleep(10); } } } cout << "end main,list size:" << myList.size() << endl; return a.exec(); } void makeListThread() { string a; MyString tempMyString; for(int i=0;i<100;i++) { QThread::msleep(0); a = to_string(i); tempMyString.valueStr = a; myMutex.lock(); myList.push(tempMyString); // 进队 myMutex.unlock(); } addThreadIsEnd = true; cout << "end addThread" << endl; }
代码来自:https://www.cnblogs.com/judes/p/11013450.html