使用多线程手动写出循环打印ABABABAB...

平时没在意,敲敲代码就出来了,可实际用笔在纸上书写的时候就不知所措了

QT比较熟悉,就用它来实现吧!

#ifndef HELLOTHREAD_H
#define HELLOTHREAD_H

#include 
#include 

class HelloThread : public QThread
{
public:
    HelloThread(int type=0);
    void stop();

protected:
    void run();

public:
    int m_type;    
    int m_exitflag;
private:
    static QMutex m_mutex;
    static int m_status;
};

#endif // HELLOTHREAD_H

#include "hellothread.h"

//静态全局变量
QMutex HelloThread::m_mutex;
int HelloThread::m_status = 0;

HelloThread::HelloThread(int type)
    : m_type(type)
{
    m_exitflag = false;
}

void HelloThread::stop()
{
    m_exitflag = true;
}

void HelloThread::run()
{
    printf("\n enter thread = %p\n", QThread::currentThreadId() );

    while( !m_exitflag )
    {
        QMutexLocker locker(&HelloThread::m_mutex);
        if(0==this->m_type && HelloThread::m_status==0)
        {
            printf("A\n");
            HelloThread::m_status = 1;//this->m_status也是可以的,但不规范
        }
        else if(1==this->m_type && HelloThread::m_status==1)
        {
            printf("B\n");
            HelloThread::m_status = 0;//this->m_status也是可以的,但不规范
        }
        locker.unlock();
        msleep(10);
    }
    m_exitflag = false;

    printf("\n leave thread = %p\n", QThread::currentThreadId() );
}


主要是用全局变量实现线程间的通讯,为了保证全局变量的状态唯一,需要加锁控制,就用最简单的QMutex吧~~~~


#include 
#include "hellothread.h"

//实现多线程,循环打印ABABABABABAB......

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

    printf("in main thread...%p\n", QThread::currentThreadId() );

    HelloThread TA(0);
    HelloThread TB(1);

    TA.start();//开启线程
    TB.start();

    if( 'q'==getchar() )//等待用户输入
    {
        TA.quit();//退出线程(不管用)
        TB.quit();

        printf("in main exiting...\n");
        TA.stop();//使用条件退出
        TB.stop();
    }

    TA.wait();//等待线程结束
    TB.wait();

    printf("in main exited thread...%p\n", QThread::currentThreadId());
    exit(0);//按键才有效,为何?

    return a.exec();
}

使用多线程手动写出循环打印ABABABAB..._第1张图片


貌似达到了目的,提笔就忘字,怎么办啊!!!

你可能感兴趣的:(编程经验)