C++ Program to Show Thread Interface and Memory Consistency Errors
C++ allows Multithreading by using the ‘thread’ header file. The program acts as one thread but to increase program execution time/performance we can use threads to run parts of the program concurrently. But it may lead to issues of memory consistency errors and may not give us the proper output. Threads are used to improve the performance of applications by running processes parallel to each other.
The thread may share the same resource or reference pointer. Two or more threads may refer to the same object or share some common resource and they try to update or make changes independently on shared resource data which can leave data inconsistent.
Example: In the below C++ program, two threads are used to use the same functions. First, it should run for thread 1 and then for thread 2. But to show memory consistency for sharing the same resource/function output is not consistent.
Example 2: In the below C++ program, an attempt will be made to access the same value from different threads as one can see memory consistency errors as both threads will run concurrently.