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

本文通过QT实现了一个简单的多线程应用案例,演示了如何利用全局变量和互斥锁(QMutex)来协调线程间的数据交换,确保了线程安全,并展示了如何控制线程的启动与停止。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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



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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值