Advance Innovation Centre
  • AIC Knowledge @ EEC for All
  • 😎Logical Thinking
    • Karel Robot
    • Code to Flowchart
    • Play with Docker
    • CNX Software
  • MCU & Interfacing with Infineon PSOC™
    • Basic MCU Interfacing
      • Introduction to CY8CKIT-062S2-43012 Pioneer Kit
      • Development Environment Preparation
      • PSoC™ 6S2 Peripherals Interfacing (GPIO)
        • Hello World and LED Blinking
        • GPIO Principles
        • PSoC™ 6S2 GPIO-HAL LED Blink Lab
        • PSoC™ 6S2 GPIO-PDL LED Blink Lab
        • Button "Bounce" Principles
          • Push/Pull Button to Turn ON/OFF LED via HAL
          • Push/Pull Button to Turn ON/OFF LED via PDL
          • GPIO Button Interrupt via HAL
          • GPIO Button Interrupt via PDL
        • GPIO variables & functions
      • PSoC™ 6S2 Peripherals Interfacing (ADC, PWM)
        • PSoC™ 6S2 SAR ADC
          • ADC Principles
          • PSoC™ 6S2 with ADC Labs
            • Reading potentiometer sensor value via an ADC HAL
            • Reading potentiometer sensor value via an ADC PDL
        • PSoC™ 6S2 PWM & TCPWM
          • PWM Principles
          • PSoC™ 6S2 for PMW Function Labs
            • LED Brightness using PWM via HAL
            • LED Brightness using PWM via PDL
    • Sensor Interfacing and HMI
      • OLED Display
        • OLED Display Principles
        • Calling BDH’s OLED functions
        • Display ADC via Potentiometer on OLED
      • BDH Shell
        • Shell Principles
        • LED Blinking and CAPSENSE via BDH Shell
        • Adding "History" command
        • Adding "Reboot" command
        • CAPSENSE Button and Slider
          • CAPSENSE Button and Slider with Capsense Tuner
          • CAPSENSE Button and Slider using FreeRTOS
    • Serial Communication & Visualization
      • UART, I2C, SPI Communication via Infineon PSoC™6
      • BMX160 Sensor Communication via Infineon PSoC™6
        • Reading ADC via HAL with Potentiometer and Displaying GUI on Serial Studio
        • Reading XENSIV-DPS-3XX Pressure Sensor and Displaying GUI on Serial Studio
        • Motion Sensors GUI Integration via Serial Studio
    • IoT Connectivity & Data Analytics via Node-Red
      • Node-Red Installation
      • Setting MQTTS to MQTT Broker
      • Sending PSoC6’s sensor to MQTT (node-red)
    • Edge AI on PSoC™
      • Machine Learning on PSoC™6 via Edge-Impulse
    • Infineon PSoC™ Troubleshooting
  • IoT Development with Infineon PSOC™ & BDH Platform
    • PSoC™ IoT Development Kit
      • Introduction to CY8CKIT-062S2-43012 Pioneer Kit
      • Development Environment Preparation
        • Hello World and LED Blinking
    • IoT Connectivity
      • Node-Red Installation
      • Controlling PSoC™ LED using MQTT
      • Setting MQTTS to MQTT Broker
      • Sending PSoC6’s sensor to MQTT (node-red)
    • BDH IoT Connectivity
    • WireLinX™ IoT PLC
    • BDH X-Brain Data Analytics
      • PSoC6 Data Collection to CSV log file
    • Data Visualization
      • สร้าง Dashboard ด้วย Looker Studio
  • 🖥️Operation Systems
    • Prerequisites
      • Guideline from Ubuntu
        • Ubuntu and VSCode on WSL2
      • ติดตั้ง WSL 2
      • Run Ubuntu on VirtualBox7
    • Zero to Linux Hero
      • Computer OS Architecture
      • Anatomy of Linux System
        • UNIX/Linux History
        • UNIX/Linux Evolution
        • GNU Project
        • Linux OS Architecture
        • Command Line Interface (CLI)
          • Basic Commands
          • 😎Level up your Linux Shell
          • File & Dir. Commands
          • Searching Commands
          • 😎ChatGPT-based Terminal
          • SysAdmin Commands
          • Network Commands
          • Hacker Commands
        • Busybox
        • Shell Script
          • Awk Script
          • Bash Shell Script
            • Bash Snippets
            • Bash Useful Examples
      • Anatomy of Linux Kernel
        • Linux Kernel Principles
        • Linux Environment for Developer
      • Anatomy of Embedded Linux
        • Embedded Linux
        • Host & Target
        • Cross Toolchains
        • Bootloader
        • Building Embedded Linux
    • Linux OS Dev. Engineer
      • Process Management
        • Process Basic
        • Process State
        • Basic Process Mgmt. Commands
        • Advance Process Mgmt. Commands
        • Process API Programming
      • IPC
        • IPC Anatomy
        • Signal Programming
        • Pipe Programming
        • FIFO Programming
        • Msg. Queue Programming
          • System V
        • Share Memory Programming
          • System V
        • Socket Programming
      • POSIX Threads
        • Multi-tasking Basic
        • POSIX Thread Anatomy
        • Threading Programming
      • Applied IPC
        • Remote Commander
        • Multi-Remote Commanders
      • Process Synchronization
        • Mutex Programming
        • Semaphore Programming
      • Applied IPC with Semaphore
  • ⌚Embedded Systems Development
    • Introduction to ESD
      • Why's ESD?
      • What it use for?
      • How it works?
    • Enbedded System Development via PSoC6
      • Basic MCU Interfacing
        • Introduction to CY8CKIT-062S2-43012 Pioneer Kit
        • Development Environment Preparation
        • PSoC™ 6S2 Peripherals Interfacing (GPIO)
          • Hello World and LED Blinking
          • GPIO Principles
          • PSoC™ 6S2 GPIO-HAL LED Blink Lab
          • PSoC™ 6S2 GPIO-PDL LED Blink Lab
          • Button "Bounce" Principles
            • Push/Pull Button to Turn ON/OFF LED via HAL
            • Push/Pull Button to Turn ON/OFF LED via PDL
            • GPIO Button Interrupt via HAL
            • GPIO Button Interrupt via PDL
          • GPIO variables & functions
        • PSoC™ 6S2 Peripherals Interfacing (ADC, PWM)
          • PSoC™ 6S2 SAR ADC
            • ADC Principles
            • PSoC™ 6S2 with ADC Labs
              • Reading potentiometer sensor value via an ADC HAL
              • Reading potentiometer sensor value via an ADC PDL
          • PSoC™ 6S2 PWM & TCPWM
            • PWM Principles
            • PSoC™ 6S2 for PMW Function Labs
              • LED Brightness using PWM via HAL
              • LED Brightness using PWM via PDL
      • Sensor Interfacing and HMI
        • OLED Display
          • OLED Display Principles
          • Calling BDH’s OLED functions
          • Display ADC via Potentiometer on OLED
        • BDH Shell
          • Shell Principles
          • LED Blinking and CAPSENSE via BDH Shell
          • Adding "History" command
          • Adding "Reboot" command
          • CAPSENSE Button and Slider
            • CAPSENSE Button and Slider with Capsense Tuner
            • CAPSENSE Button and Slider using FreeRTOS
      • Serial Communication & Visualization
        • UART, I2C, SPI Communication via Infineon PSoC™6
        • BMX160 Sensor Communication via Infineon PSoC™6
          • Reading ADC via HAL with Potentiometer and Displaying GUI on Serial Studio
          • Reading XENSIV-DPS-3XX Pressure Sensor and Displaying GUI on Serial Studio
          • Motion Sensors GUI Integration via Serial Studio
    • Edge Computing and IoT Connectivity
    • Cloud-Based Data Analytics and Digital Twin
    • Edge Vision AI
    • Resources
      • Basic Hardware and Firmware
        • Environment Preparation
          • การติดตั้งโปรแกรม Arduino IDE
            • ตัวอย่างการเริ่มต้นใช้งาน Arduino IDE
          • การติดตั้งโปรแกรมสำหรับใช้งานเครื่องมือวัด NI MyDAQ
            • ตัวอย่างการตั้งค่าใช้ Digital Multimeter -NI ELVISmx
            • ตัวอย่างการตั้งค่าใช้ Oscilloscope-NI ELVISmx
          • ติดตั้งโปรแกรม KingstVIS
        • Basic measurement
          • Basic Digital and Analog I/O
            • LAB: Basic Digital Input/Output
            • LAB: Basic Analog Input/Output
          • Waveform
            • LAB: Oscilloscope
            • LAB: Oscilloscope and Function Generator
            • LAB: Pulse Width Modulation (PWM)
              • Homework
        • Interfacing and Communication
          • LAB: UART, RS485, RS232 Protocol
          • LAB: I2C Protocol
            • HOMEWORK
          • LAB: SPI Protocol
      • IoT Connectivity
        • Example: IoT with MQTT on Node-red
        • Data logger
        • LAB: Data Visualization
  • 🛠️C/C++ for Embedded Programming
    • Development Environment Preparation
      • ติดตั้ง WSL 2
      • ติดตั้ง Ubuntu environment
      • ติดตั้งโปรแกรม Visual Studio Code
      • การเชื่อมต่อ Virtual studio code เข้ากับ WSL
      • ติดตั้ง docker on WSL
    • Principle C/C++ Programming
      • Get started with C++
      • Makefile
        • Makefile Examples
      • Compiling and running
        • How to create a program that you can enter inputs.
          • Lab 1 Exercise
      • Arguments
        • Command line arguments in C and C++
      • signed and unsigned data types
      • Variable and Operator
      • If and If else
      • Loop, Infinite loop, and flag
        • Loop and Flag exercise
      • Array
        • Get to know with arrays
        • Implement example
      • Vector
    • Object Oriented Programming (OOP) in C++
      • Class and Object
      • Encapsulation and Abstraction
      • Polymorphism and Inheritance
    • C/C++ Preprocessing
      • Macro
        • Quiz Macro
      • File Inclusion
      • Conditional Compilation
      • Pragma directive
        • Quiz Pragma
    • String in C++
      • Concatenation
      • Split
    • Type conversions for C/C++
      • Conversion using Cast operator
    • Error handling
    • Data logger
      • การสร้างไฟล์และเขียนไฟล์
      • การอ่านไฟล์
      • การเก็บข้อมูลกับTime stamp
    • High performance programing
      • Multi-task and Multi-thread
        • Multi-threading example
      • Mutex
      • Queue
      • OpenCV
    • C/C++ Techniques
      • Makefile in action
      • Object Oriented Programming (OOP) in C++
        • Class and Object
        • Encapsulation and Abstraction
        • Polymorphism and Inheritance
      • C/C++ Preprocessing
        • Macro
          • Quiz Macro
        • File Inclusion
        • Conditional Compilation
        • Pragma directive
          • Quiz Pragma
      • Binary, Octal and Hexadecimal Numbers
      • Array and properties of an array
        • Get to know with arrays
        • Implement example
      • What's next?
  • 🤖Artificial Intelligence (AI)
    • VAMStack Design House, BUU
    • Data Analytics
      • Data cleansing
      • Data analytics
      • Data analytic exercise
    • Machine Learning
      • Neural Network Layers
      • Machine learning type
      • Dataset
      • Using Edge Impulse for AI Model
    • Basic Image Processing
      • Computer Vision using Python Language
        • Installation
        • Computer Vision Basics
          • Pixel and Color
          • Draw image
          • Basic Image processing
          • Morphology Transformations
          • Gaussian blur
          • Simple Thresholding
          • Contour
          • Canny edge detection
        • Case Study
          • Coin counting
          • Color detection & tracking
        • VAM_CV SDK
  • ⚙️FPGA Design and Development
    • Verilog HDL via Vivado IDE
      • LAB1: Setting Environment and Create Project
        • Create Vivado Project
      • LAB2: Hardware Description Language Work Flow
        • Simulation code
      • LAB3: Design HDL Project
        • Top Level Design
        • Top-level Simulation
      • LAB4: Asynchronous VS Synchronous Circuit
        • Simulation Synchronous counter
    • C/C++ Programming on Ultra96v2 FPGA Board
      • Application C/C++ on Ultra96v2 Part 1
        • Design Overview
        • Step 1 - Burn the image to SD card
        • Step 2 - Bring up Ultra96v2
        • Step 3 - Installing the Vitis-AI runtime packages
      • Application C/C++ on Ultra96v2 Part 2
        • STEP 1 : Setting auto boot Wifi
        • STEP 2 : How to working on Embedded
        • STEP 3 : How to run the test code
  • 🤖Robotics
    • Dobot Magician
      • Instruction of Dobot
      • Software Download
      • Basically of Program
        • Teaching and Playback
        • Write and Draw
        • LaserEngraving
        • 3D Printer
    • Robotino
      • Software Download
        • Robotino View
        • Robotino SIM
      • Charging
      • Connecting
      • Follow Line example
        • Basic block in Follow Line
    • RaspBlock
      • Get Started with Raspblock
  • 🚩Special Topics
    • Node-Red
      • Set up Raspberry Pi
      • Install node red in Raspberry Pi
      • Get started with Node Red
        • Open node-red
        • Turn off node red
        • Install Dashboard on Node-red
        • Use node red to show message
        • Using Ultrasonic sensor with node-red
    • IoT Cloud
      • Overview
        • How do they work?
          • Basic Knowlege
      • Installations
        • Install Docker
        • Install Mosquitto Broker
        • Install InfluxDB
        • Install Telegraf
        • Install Grafana
      • Get Sensor Value and Send to MQTT
        • Connect ESP3266 to sensor
        • Connect ESP3266 to MQTT
      • Integration
    • Senses IoT
      • SENSES IoT Platform
      • LAB8: MCU send data to IoT platform
    • CrowPi Dev Kit
      • Raspberry Pi with CrowPi
      • Remote to Raspberry Pi
      • Cross-Compile
        • Lab 1: Programming and cross complier
      • Hardware and Interfaces Usage CLI
        • LAB: Usage GPIO via CLI
        • LAB: Scan I2C bus via CLI
      • Python library for Crow Pi
      • wiringPi library (C) for CrowPi
        • Lab2: Crowpi and sensors
    • LVGL Development
      • LVGL - Light and Versatile Embedded Graphics Library
        • Setting program for LVGL Simulator
        • Get started with LVGL simulator
        • Example Library of LVGL
        • Create your own screen
          • Exercise
        • Style
          • Exercise
        • Event
    • Docker OS
      • Docker OS Part 1
        • Part 1 : Installation
        • Part 2 : Basic Docker OS and Linux CLI
      • Docker OS Part 2
        • Part 1 : Docker communication
        • Part 2 : Docker compose
      • Application Gstreamer on devcontainer
        • STEP 1 : Setting gstreamer environment
        • STEP 2 : Create the Gstreamer element on template
        • STEP 3 : Testing and application on your gst element
  • 🤟Recommended by AIC
    • Skill Roadmap
      • Embedded Engineer
      • Developer
    • Hardware Programming
    • Embedded Programming
    • General-propose Programming
    • Algorithmica
    • Thai Expert Knowledge
    • RT-Thread University Program
      • Infineon PSoC6
      • Kernel
        • Kernel Basics
        • Thread Management
        • Clock Management
        • Inter-thread synchronization
        • Inter-thread communication
        • Memory Management
        • Interrupt Management
        • Kernel porting
        • Atomic Operations
        • RT-Thread SMP
        • Kernel API Changelog
      • Tools
      • Devices & Drivers
        • SENSOR Devices
        • Touch Equipment
        • CRYPTO Devices
        • AUDIO Devices
        • Pulse Encoder Devices
      • Components
        • C Library (libc)
        • ISO/ANSI C Standard
        • POSIX Standard
          • FILE (File IO)
          • Pthread
          • Timer
          • IPC Semaphore
          • IPC Message Queues
          • Dynamic Modules
        • Network Components
          • FinSH Console
          • FAL: Flash Abstraction Layer
          • Virtual File System
          • tmpfs: temporary file system
          • ulog log
          • utest testing framework
          • Power Management
          • RT-Link
        • Software Packages
          • Internet of Things
            • MQTT-umqtt
            • Telnet
          • Tools
            • SystemView
            • SEGGER_RTT
          • LVGL Manual
            • Touch Screen Driver
      • Demo
        • Infineon Gateway
        • Handwriting Recognition (MNIST)
        • Object Detection (Darknet)
        • ROS using RT-Thread
        • Control the car using RT-Thread
        • LiDAR via RT-Thread
        • Detection via RT-Thread and ROS
        • Sensor Driver Development Guide
Powered by GitBook

Assoc. Prof. Wiroon Sriborrirux, Founder of Advance Innovation Center (AIC) and Bangsaen Design House (BDH), Electrical Engineering Department, Faculty of Engineering, Burapha University

On this page
  • Introduction to atomic operations
  • Advantages of atomic operations
  • Implementation and usage of RT-Thread atomic operations
  • RT-Thread Atomic Operation API
  • Comprehensive Example

Was this helpful?

  1. Recommended by AIC
  2. RT-Thread University Program
  3. Kernel

Atomic Operations

PreviousKernel portingNextRT-Thread SMP

Last updated 7 months ago

Was this helpful?

An atomic operation refers to an indivisible operation that is either executed completely successfully or not executed at all. No interruptions are allowed during the execution of an atomic operation. If an interruption occurs, the result of the operation cannot be guaranteed. Atomic operations are often used in multi-threaded programming to ensure that concurrent execution between multiple threads does not cause problems such as data contention. When implementing atomic operations, hardware instructions or atomic operation functions provided by the operating system are usually used to ensure the atomicity of the operation. At the application level, atomic operations can be used to implement some advanced synchronization and concurrency control mechanisms. For example, in multi-threaded programming, if multiple threads need to access the same shared variable, in order to avoid data contention problems, atomic operations can be used to ensure that operations on the variable are atomic. Let's take the ARM kernel executing an i++ operation as an example:

movl i, %eax                            //内存访问,读取 i 变量到 cpu 的 eax 寄存器
addl $1, %eax                           //修改寄存器的值
movl %eax, i                            //将寄存器中的值写回内存copymistakeCopy Success

We see that for coding engineers, we only need one line of code to execute an i++ operation. After compilation, i++ will be translated into three instructions. Therefore, these three instructions may be interrupted by system scheduling, interrupts and other events. Therefore, in some scenarios, we need to execute the above operations in one go. Atomic operations have this capability.

In RT-Thread, we can protect critical section resources by switching global interrupts, locking the scheduler, etc. Other OSes also provide similar operations. If atomic operations are used, we can improve the execution efficiency of critical section codes and greatly improve the operating efficiency of the system. At the same time, it will also reduce the complexity of programming to a certain extent. The following is an example of a simple variable increment:

The protection of critical area is realized by switching global interrupt:

  ...  
    int a = 5;
    level = rt_hw_interrupt_disable();
    a++;
    rt_hw_interrupt_enable(level);
  ...copymistakeCopy Success

If we use the atomic operation API provided by RT-Thread, we can do this:

  ...      
    int a = 5;
    rt_atomic_add(&a,1);
  ...  copymistakeCopy Success

Obviously, the atomic operation method is simpler and avoids the performance loss caused by switching global interrupts.

RT-Thread provides atomic operation support for 32-bit ARM, 32-bit RISC-V and 64-bit RISC-V cores that support atomic operations. It uses the atomic operation instructions and related instructions of the corresponding platform to implement it. It is supported by default and users do not need to worry about the implementation. When using it, users only need to include it in the project rtatomic.hto use the atomic operation API provided by the file. The detailed support is as follows:

Instruction architecture

Atomic instruction support of RT-Thread adapter kernel

32-bit ARM

Most cores using the ARM instruction set support atomic instructions. The cores that do not support atomic instructions include cortex-m0, cortex-m0+, arm926, lpc214x, lpc24xx, s3c24x0, and AT91SAM7.

32-bit RISC-V

Most kernels using the RV32 instruction set support atomic operations. Some BSPs that do not support atomic operations include: core-v-mcu, rv32m1_vega.

64-bit RISC-V

Most kernels using the RV64 instruction set support atomic operations. Some BSPs that do not support atomic operations include juicevm.

If the tool chain supports the atomic operation API of the C11 standard, you can also use menuconfig to configure RT_USING_STDC_ATOMICthe macro. In this case, rtatomic.hthe macro provided in the call will actually call the API provided by the C11 standard. The configuration method of menuconfig is as follows:

RT-Thread Kernel --->
   [*]Use atomic implemented in stdatomic.hcopymistakeCopy Success

For the above kernels that do not support atomic operations, when users include and use the API provided by this file in their projects rtatomic.h, atomic operations will be soft-implemented by switching global interrupts.

RT-Thread provides 11 frequently used atomic operation APIs.

RT-Thread Atomic Operation API

effect

rt_atomic_t rt_hw_atomic_load(volatile rt_atomic_t *ptr)

Atomically load a word from address ptr

void rt_atomic_store(volatile rt_atomic_t *ptr, rt_atomic_t val)

Atomically write val to address ptr

rt_atomic_t rt_atomic_exchange(volatile rt_atomic_t *ptr, rt_atomic_t val)

Atomically replace the value at the address of ptr with val

rt_atomic_t rt_atomic_add(volatile rt_atomic_t *ptr, rt_atomic_t val)

Atomically adds the value at address ptr to val

rt_atomic_t rt_atomic_sub(volatile rt_atomic_t *ptr, rt_atomic_t val)

Atomically subtract the value at address ptr from val

rt_atomic_t rt_atomic_xor(volatile rt_atomic_t *ptr, rt_atomic_t val)

Atomically XOR the value at address ptr with val

rt_atomic_t rt_atomic_and(volatile rt_atomic_t *ptr, rt_atomic_t val)

Atomically AND the value at address ptr with val

rt_atomic_t rt_atomic_or(volatile rt_atomic_t *ptr, rt_atomic_t val)

Atomically bitwise OR the value at address ptr with val

rt_atomic_t rt_atomic_flag_test_and_set(volatile rt_atomic_t *ptr)

Atomically sets the value at address ptr to 1

void rt_atomic_flag_clear(volatile rt_atomic_t *ptr)

Atomically clear the value at the address ptr to 0

rt_atomic_t rt_atomic_compare_exchange_strong(volatile rt_atomic_t *ptr, rt_atomic_t *old, rt_atomic_t new)

Atomically compares and exchanges the value at the address ptr with val, and returns the comparison result

Detailed explanation of atomic operation functions:

rt_atomic_t rt_atomic_load(volatile rt_atomic_t *ptr);copymistakeCopy Success

The semantics of this operation function is: use atomic operation to load a word from the 4-byte space pointed to by the ptr address.

parameter

describe

ptr

Atomic object address

Return Value

Returns the 4-byte data at the address of ptr

void rt_atomic_store(volatile rt_atomic_t *ptr, rt_atomic_t val);copymistakeCopy Success

The semantics of this operation function is: use atomic operation to write val into the 4-byte space pointed to by the ptr address.

parameter

describe

ptr

Atomic object address

val

Expected data to be written to the address ptr

Return Value

NULL

rt_atomic_t rt_atomic_exchange(volatile rt_atomic_t *ptr, rt_atomic_t val);copymistakeCopy Success

The semantics of this operation function is: use atomic operation to exchange the data in the 4-byte space pointed to by the ptr address with val, and return the 4-byte data before modification at the ptr address.

parameter

describe

ptr

Atomic object address

val

Expected data to be exchanged

Return Value

Returns the 4 bytes of data before the swap at the ptr address

rt_atomic_t rt_atomic_add(volatile rt_atomic_t *ptr, rt_atomic_t val);copymistakeCopy Success

The semantics of this operation function is: use atomic operation to add the 4-byte data pointed to by the ptr address to val, write the result to the 4-byte space pointed to by the ptr address, and return the 4-byte data before modification at the ptr address.

parameter

describe

ptr

Atomic object address

val

Expected value to be added

Return Value

Returns the 4 bytes of data before modification at the ptr address

rt_atomic_t rt_atomic_sub(volatile rt_atomic_t *ptr, rt_atomic_t val);copymistakeCopy Success

The semantics of this operation function is: use atomic operation to subtract val from the 4-byte data pointed to by the ptr address, write the result to the 4-byte space pointed to by the ptr address, and return the 4-byte data before modification at the ptr address.

parameter

describe

ptr

Atomic object address

val

Expected value to be subtracted

Return Value

Returns the 4 bytes of data before modification at the ptr address

rt_atomic_t rt_atomic_xor(volatile rt_atomic_t *ptr, rt_atomic_t val);copymistakeCopy Success

The semantics of this operation function is: use atomic operation to perform bitwise XOR on the 4-byte data pointed to by the ptr address and val, write the result to the 4-byte space pointed to by the ptr address, and return the 4-byte data before modification at the ptr address.

parameter

describe

ptr

Atomic object address

val

Expected XOR value

Return Value

Returns the 4 bytes of data before modification at the ptr address

rt_atomic_t rt_atomic_and(volatile rt_atomic_t *ptr, rt_atomic_t val);copymistakeCopy Success

The semantics of this operation function is: use atomic operation to perform bitwise AND operation on the 4-byte data pointed to by the ptr address and val, write the result to the 4-byte space pointed to by the ptr address, and return the 4-byte data before modification at the ptr address.

parameter

describe

ptr

Atomic object address

val

Expected value to be ANDed

Return Value

Returns the 4 bytes of data before modification at the ptr address

rt_atomic_t rt_atomic_or(volatile rt_atomic_t *ptr, rt_atomic_t val);copymistakeCopy Success

The semantics of this operation function is: use atomic operation to perform bitwise OR of the 4-byte data pointed to by the ptr address and val, write the result to the 4-byte space pointed to by the ptr address, and return the 4-byte data before modification at the ptr address.

parameter

describe

ptr

Atomic object address

val

Expected OR value

Return Value

Returns the 4 bytes of data before modification at the ptr address

rt_atomic_t rt_atomic_flag_test_and_set(volatile rt_atomic_t *ptr);copymistakeCopy Success

The semantics of this operation function is: set the 4-byte atomic flag pointed to by the ptr address, and return the value of the atomic flag object before the setting operation. If the 4-byte data pointed to by the ptr address was previously in state 0, then after this operation, the state of the atomic flag object changes to state 1, and returns 0. If the 4-byte data pointed to by the ptr address was previously in state 1, then after this operation, it is still in state 1, and returns 1. So if we use the atomic flag object as a "lock", we can judge the return value of this function interface. If it returns 0, it means that the lock is successful, and related modification operations can be performed on the multi-threaded shared object; if the return is state 1, the atomic flag has been occupied by other threads and needs to wait for release.

parameter

describe

ptr

Atomic object address. The 4-byte data pointed to by the address can only be 0 or 1.

Return Value

Set Status

void rt_atomic_flag_clear(volatile rt_atomic_t *ptr);copymistakeCopy Success

The semantics of this operation function is: clear the flag, clear the flag to 0, and clear the atomic flag pointed to by the ptr address. If we use the atomic flag object as a "lock", then performing this operation is equivalent to releasing the lock.

parameter

describe

ptr

Atomic object address

Return Value

NULL

rt_atomic_t rt_atomic_compare_exchange_strong(volatile rt_atomic_t *ptr, rt_atomic_t *old, rt_atomic_t new);copymistakeCopy Success

The semantics of this operation function is: the first parameter points to an atomic type object; the second parameter points to the object to be compared, and if the comparison fails, the operation will copy the current value of the atomic object to the object pointed to by the parameter; the third parameter specifies the value stored in the atomic object. If the comparison succeeds, the new value will be stored in the atomic object and 1 will be returned; if the comparison fails, the value of the current atomic object will be copied to the object pointed to by old and 0 will be returned.

parameter

describe

ptr

Atomic object address

old

Objects being compared

new

The object to be updated

Return Value

Comparison results

Include it in your project rtatomic.h, and then add the example to your project for simple atomic operation verification.

/* 在工程中添加该头文件 */
#include <rtatomic.h>

rt_atomic_t value1 = 10;
rt_atomic_t value2 = 5;
int main(void)
{
    /* atomic add */
    result = rt_atomic_add(&value1, value2);
    rt_kprintf("result = %d value1 = %d value2 = %d\r\n", result, value1, value2);

    value1 = 10;
    value2 = 5;
    /* atomic sub */
    result = rt_atomic_sub(&value1, value2);
    rt_kprintf("result = %d value1 = %d value2 = %d\r\n", result, value1, value2);

    value1 = 10;
    value2 = 5;
    /* atomic xor */
    result = rt_atomic_xor(&value1, value2);
    rt_kprintf("result = %d value1 = %d value2 = %d\r\n", result, value1, value2);

    value1 = 10;
    value2 = 5;
    /* atomic or */
    result = rt_atomic_or(&value1, value2);
    rt_kprintf("result = %d value1 = %d value2 = %d\r\n", result, value1, value2);

    value1 = 10;
    value2 = 5;
    /* atomic and */
    result = rt_atomic_and(&value1, value2);
    rt_kprintf("result = %d value1 = %d value2 = %d\r\n", result, value1, value2);

    value1 = 10;
    value2 = 5;
    /* atomic exchange */
    result = rt_atomic_exchange(&value1, value2);
    rt_kprintf("result = %d value1 = %d value2 = %d\r\n", result, value1, value2);

    value1 = 10;
    value2 = 5;
    /* atomic compare and exchange */
    result = rt_atomic_compare_exchange_strong(&value1, value2, 6);
    rt_kprintf("result = %d value1 = %d value2 = %d\r\n", result, value1, value2);

    value1 = 10;
    /* atomic load */
    result = rt_atomic_load(&value1);
    rt_kprintf("result = %d value1 = %d value2 = %d\r\n", result, value1, value2);

    value1 = 10;
    value2 = 5;
    /* atomic store */
    result = rt_atomic_store(&value1, value2);
    rt_kprintf("result = %d value1 = %d value2 = %d\r\n", result, value1, value2);

    value1 = 0;
    /* atomic flag test and set */
    result = rt_atomic_flag_test_and_set(&value1);
    rt_kprintf("result = %d value1 = %d value2 = %d\r\n", result, value1, value2);

    /* atomic flag clear */
    result = rt_atomic_flag_clear(&value1);
    rt_kprintf("result = %d value1 = %d value2 = %d\r\n", result, value1, value2);
}copymistakeCopy Success

🤟
Introduction to atomic operations
Advantages of atomic operations
Implementation and usage of RT-Thread atomic operations
RT-Thread Atomic Operation API
Atomic read
Atomic Write
Atomic Data Exchange
Atomic Add
Atomic Subtraction
Atomic XOR
Atom and
Atom or
Atomic flag checking and setting
Atomic flag clearing
Atomic compare and swap
Comprehensive Example