多线程的创建与运行

本文介绍如何在C语言中创建并运行多线程,通过示例展示了线程的执行流程,包括头文件引用、源文件编写及main函数中的操作,最终输出了特定的运行成功标志。

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

多线程的创建与运行

关于多线程的使用无论是C、C++还是Java等其他语言都用的比较多
以下以QT的C++为例创建并运行多线程;
并测试是否多线程同时运行(成功标志为两个无序间隔输出)

头文件:

#ifndef THREAD_H
#define THREAD_H

#include <QThread>
#include <iostream>

class thread:public QThread
{
    Q_OBJECT
public:
    thread();
    void setMessage(QString message);
    void stop();
    int flag = 0;

protected:
    void run();
    void printMessage();
    void printMessage1();

private:
    QString messageStr;
    volatile bool stopped;
};

#endif // THREAD_H

源文件:

#include "thread.h"
#include <QDebug>

thread::thread(){
}
void thread::run(){
    if(flag == 0)
        printMessage();
    else
        printMessage1();
}

void thread::stop(){
}

void thread::setMessage(QString message){
    messageStr = message;
}

void thread::printMessage(){
    for(int i=5;i>0;i--){
        qDebug()<<i;
    }
    qDebug()<<messageStr;

}
void thread::printMessage1(){
    for(int i=5;i>0;i--){
        qDebug()<<"g";
    }
    qDebug()<<messageStr;

}

main文件:

#include "thread.h"

int main(){
    thread thread1;
    thread thread2;
    thread1.flag = 1;
    thread2.flag = 0;
    thread1.setMessage("A");
    thread2.setMessage("B");
    thread1.start();
    thread2.start();
    thread1.wait();
    thread2.wait();
}

运行成功标志:
5
4
g
3
g
2
g
1
g
“B”
g
“A”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

昔年年年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值