您的位置:首页 > 其它

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

2017-12-27 14:52 239 查看
平时没在意,敲敲代码就出来了,可实际用笔在纸上书写的时候就不知所措了


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

#ifndef HELLOTHREAD_H
#define HELLOTHREAD_H

#include <QThread>
#include <QMutex>

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 <QCoreApplication>
#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();
}




貌似达到了目的,提笔就忘字,怎么办啊!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐