【QT5 多线程示例】原子操作

原子操作

【C++并发编程】(五)原子操作

在Qt5中,主要有两种原子变量:

  • QAtomicInteger<T>(用于整数类型的原子操作)
  • QAtomicPointer<T>(用于指针的原子操作)

下面给出两种变量的例子:

QAtomicInteger 示例(线程安全的计数器)

https://github.com/BinaryAI-1024/QtStudy/tree/master/thread/atomicinteger

cpp 复制代码
#include <QCoreApplication>
#include <QAtomicInteger>
#include <QThread>
#include <QDebug>

QAtomicInteger<int> counter(0);  // 线程安全的计数器

void threadFunc() {
    for (int i = 0; i < 10; ++i) {
        // 原子递增,多个线程操作时不会出现数据竞争
        counter.fetchAndAddRelaxed(1);
        QThread::msleep(100);  // 模拟工作
    }
}

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

    // 使用 QThread::create 创建线程
    QThread *t1 = QThread::create(threadFunc);
    QThread *t2 = QThread::create(threadFunc);

    t1->start();
    t2->start();

    t1->wait();
    t2->wait();

    qDebug() << "Final counter value:" << counter.load();

    delete t1;
    delete t2;

    return 0;
}
复制代码
Final counter value: 20

QAtomicPointer示例(线程安全地存取指针)

https://github.com/BinaryAI-1024/QtStudy/tree/master/thread/atomicpointer

cpp 复制代码
#include <QCoreApplication>
#include <QAtomicPointer>
#include <QThread>
#include <QDebug>

struct Node {
    int value;
};

QAtomicPointer<Node> atomicPtr(nullptr);

void threadFunc() {
    Node* newNode = new Node{42};
    atomicPtr.store(newNode);  // 线程安全地存储指针
}

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

    QThread *t = QThread::create(threadFunc);

    t->start();
    t->wait();

    qDebug() << "Atomic Pointer Value:" << atomicPtr.load()->value;

    delete atomicPtr.load();  // 释放内存
    return 0;
}
复制代码
Atomic Pointer Value: 42
相关推荐
sm_926787051 小时前
RFID 标签打印的技术实现要点与二次开发实践
java·大数据·前端·c++·编辑器
by209991 小时前
C++ 多态:同一个基类接口,调用不同的函数
开发语言·c++·经验分享·多态
bug和崩溃我都要2 小时前
QT 开发的专业截图录屏工具 - macOS版 / Windows版
windows·qt·mac·录屏·截屏
colinu2 小时前
C++ 异步任务与线程生命周期:`std::async`、`future`、`thread`、`jthread` 与协作式退出
java·jvm·c++
wuminyu3 小时前
ForkJoinPool窃取线程在扫描其他WorkQueue时的随机采样算法与Phase线程挂起唤醒机制解析
java·linux·c语言·jvm·c++
longlongzihan3 小时前
链表找环:Floyd 判圈算法(LeetCode 141 & 142 )
c++·算法·leetcode·链表
liulilittle3 小时前
Linux 下 select 测试函数
linux·服务器·网络·数据库·c++·select·c
无忧.芙桃4 小时前
C++语言原理与实践(十二):list类的底层实现
c++·windows·list
沫璃染墨4 小时前
《Linux工程实践篇(二):线程池实战——从线程安全单例到完整源码实现》
linux·开发语言·c++·单例模式·设计模式·系统架构
有只小白叫岳飒4 小时前
c++智能指针 unique_ptr与函数调用
c++