Horje
How to Use the Volatile Keyword in C++?

In C++, the volatile keyword is used to tell the compiler that the value of the variable declared using volatile may change at any time. In this article, we will learn how to use the volatile keyword in C++.

Volatile Keyword in C++

We can use the volatile keyword for different purposes like declaring some global variables, variables across shared threads, etc.

Syntax to use Volatile Keyword in C++

volatile dataType varName;

C++ Program to Show the Use of Volatile Keyword

C++

// C++ Program to Show how to use the Volatile Keyword
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
  
// Mutex for synchronization
mutex mtx;
  
// Volatile variable to be accessed by multiple threads
volatile int volVar = 0;
  
// Function to increment the volatile variable
void incValue()
{
    for (int i = 0; i < 10; i++) {
        mtx.lock(); // Lock the mutex before accessing
                    // volVar
        volVar++;
        mtx.unlock(); // Unlock the mutex after modifying
                      // volVar
    }
}
  
int main()
{
    // Create two threads to increment volVar
    thread t1(incValue);
    thread t2(incValue);
  
    // Wait for both threads to finish
    t1.join();
    t2.join();
  
    // Output the final value of volVar
    cout << "Final value of volVar: " << volVar << endl;
  
    return 0;
}

Output

Final value of volVar: 20

Time Complexity: O(1), for each lock and unlock operation.
Auxiliary Space: O(1)




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Read a Paragraph of Text with Spaces in C++? How to Read a Paragraph of Text with Spaces in C++?
How to Find the Mode in a Sorted Array in C++? How to Find the Mode in a Sorted Array in C++?
How to Implement Priority Queue Using Multimap in C++? How to Implement Priority Queue Using Multimap in C++?
How to Find First Occurrence of an Element in a Set in C++? How to Find First Occurrence of an Element in a Set in C++?
How to Check if a Vector Contains a Given Element in C++? How to Check if a Vector Contains a Given Element in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14