qt_线程2

线程的安全退出

#ifndef MYTHREAD_H
#define MYTHREAD_H
#include<QThread>
#include<QMutexLocker>
/*
 * QThread::currentThreadId();          thread name(id) of now
 * thread exit  (use connect sinal to display thread)
 * way one:
 * --------------way one-----------------
 * private:
 *       bool m_bStopped;
 *       QMutex m_mutex;
 * code as file ........
 * 
 * --------------way two----------------
 * class WorkerThread : public QThread
{
    Q_OBJECT

public:
    explicit WorkerThread(QObject *parent = 0)
        : QThread(parent)
    {
    }

    ~WorkerThread() {
        // 请求终止
        requestInterruption();
        quit();
        wait();
    }

protected:
    virtual void run() Q_DECL_OVERRIDE {
        // 是否请求终止
        while (!isInterruptionRequested())
        {
            // 耗时操作
        }
    }
};
 *
*/
class MyThread:public QThread
{
public:
    MyThread();
    ~MyThread();
protected:
    virtual void run();
signals:
    void runComplete(int value);
private:
    void stop();
    bool m_bStopped;
    QMutex m_mutex;
};

#endif // MYTHREAD_H




#include "mythread.h"

MyThread::MyThread()
{
    m_bStopped=false;

}
MyThread::~MyThread()
{
    stop();
    quit();
    wait();
}
//thread exit 
MyThread::stop()
{
    qDebug()<<"thread exit:"<<QThread::currentThreadId();
    //==========judge exit============
    QMutexLocker locker(&m_mutex);
    m_bStopped = true;
}
void MyThread::run()
{
    qDebug()<<"thread start"<<QThread::currentThreadId();
    while(1)
    {
        QMutexLocker locker(&m_mutex);
        if (m_bStopped)
            break;
    }
}

线程的同步
生产者消费者(wait的同步方式,还有种信号量的)

/*
生产者不能生产超过缓存,消费者不能从空的缓存中获取产品,所以在缓存仓库满的时候,生产者必须等待,在仓库空时候消费者必须等待。
出现了两个等待的条件Empty and Full
如果需要判断是否满,那就需要数量的掌控,可用的产品数量numusebyte
以上进行了同步的条件,因为numusebyte需要进行互斥操作,出现了mutex
*/
#ifndef PRODUCER_H
#define PRODUCER_H
#include<QWaitCondition>
#include<QTime>
#include<QMutex>
#include<QThread>

const int DataSize = 100000;

const int BufferSize = 8192;
char buffer[BufferSize];

QWaitCondition bufferNotEmpty;
QWaitCondition bufferNotFull;
QMutex mutex;
int numUsedBytes = 0;
class Producer : public QThread
{
public:
    Producer(QObject *parent = NULL) : QThread(parent)
    {
    }

    void run() Q_DECL_OVERRIDE
    {
        qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));

        for (int i = 0; i < DataSize; ++i) {
            mutex.lock();
            if (numUsedBytes == BufferSize)
                bufferNotFull.wait(&mutex);
            mutex.unlock();

            buffer[i % BufferSize] = "ACGT"[(int)qrand() % 4];

            mutex.lock();
            ++numUsedBytes;
            bufferNotEmpty.wakeAll();
            mutex.unlock();
        }
    }
};


class Consumer : public QThread
{
public:
    Consumer(QObject *parent = NULL) : QThread(parent)
    {
    }

    void run() Q_DECL_OVERRIDE
    {
        for (int i = 0; i < DataSize; ++i) {
            mutex.lock();
            if (numUsedBytes == 0)
                bufferNotEmpty.wait(&mutex);
            mutex.unlock();

            fprintf(stderr, "%c", buffer[i % BufferSize]);

            mutex.lock();
            --numUsedBytes;
            bufferNotFull.wakeAll();
            mutex.unlock();
        }
        fprintf(stderr, "\n");
    }

signals:
    void stringConsumed(const QString &text);
};
#endif // PRODUCER_H


#include "producer.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    Producer producer;
    Consumer consumer;
    producer.start();
    consumer.start();
    producer.wait();
    consumer.wait();
    return 0;
}



多线程ping地址

#ifndef MYTHREAD_H
#define MYTHREAD_H
#include<QThread>
#include<QDebug>
#include<QFile>

/*
 * QThread::currentThreadId();          thread name(id) of now
*/
QString file_name="~/ip.txt";
class MyThread:public QThread
{

public:
    explicit MyThread(QString ip):IP(ip){

    }

    ~MyThread(){
            quit();
            wait();
        }

protected:
    virtual void run(){
        system(QString("ping -c 1 -W 1 %1 |grep  -B 1 '1 received'|"
                       "sed  -n  's/.*\\(125.217.37.[1-9]\\{1,3\\}\\).*/\\1/p'>>%2").
               arg(IP).arg(file_name).toStdString().c_str());
    }

private:
    QString IP;

};

#endif // MYTHREAD_H


#include "mythread.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    system(QString("rm %1").arg(file_name).toStdString().c_str());

    //------------- construct IP list-----------------
    for(int i=0;i<255;i++)
        (new MyThread(QString("125.217.37.%1").arg(i)))->start();
    return 0;
}

qt_线程2
多线程ping ip地址(线程池)

 #-------------------------------------------------
#
# Project created by QtCreator 2019-04-01T20:40:10
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = Mywin
TEMPLATE = app


SOURCES += main.cpp

HEADERS  += widget.h \
    mythread.h


#ifndef MYTHREAD_H
#define MYTHREAD_H
#include<QRunnable>
#include<QDebug>
#include<QThread>
#include<QFile>

/*
 * QThread::currentThreadId();          thread name(id) of now
*/
QString file_name="~/ip.txt";
class MyThread:public QRunnable,public QObject
{

public:
    explicit MyThread(QString ip):IP(ip){}

protected:
    virtual void run(){
               qDebug()<<"thread ID:"<< QThread::currentThreadId()<<"\tIP:"<<IP;
        system(QString("ping -c 1 -W 1 %1 |grep  -B 1 '1 received'|"
                       "sed  -n  's/.*\\(125.*.[1-9]\\{1,3\\}\\).*/\\1/p' >>%2").
               arg(IP).arg(file_name).toStdString().c_str());
    }


private:
    QString IP;

};

#endif // MYTHREAD_H



#include "mythread.h"
#include <QThreadPool>
#include <QApplication>

/*
 * QRunnable:
 * virtual void run()
 * void QRunnable :: setAutoDelete(bool autoDelete)
 *
 * QThreadPool:
 * void	setMaxThreadCount(int maxThreadCount)           max number of thread
 * void	start(QRunnable *runnable, int priority = 0)    run thread
 * void	setExpiryTimeout(int expiryTimeout)             thread run time
 * int	activeThreadCount() const                        active thread
 *
 *
*/
int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    system(QString("rm %1").arg(file_name).toStdString().c_str());
     QThreadPool pool;
     pool.setMaxThreadCount(100);//max number of thread

    //------------- construct IP list-----------------
        for(int i=0;i<255;i++)
             for(int j=20;j<50;j++)
                pool.start(new MyThread(QString("125.217.%2.%1").arg(i).arg(j)));
            return 0;
}


qt_线程2