On 15th August - my contribution to the learning community...
Concurrency profiling in C++ is essential for optimizing the performance of multi-threaded applications by identifying and addressing bottlenecks, inefficiencies, and issues like race conditions and deadlocks.
I am using the Helgrind tool of Valgrind in eclipse to do the experimentation on C++ data race condition in a multithreaded application.
A data race occurs in a multithreaded application when two or more threads access shared data concurrently, and at least one of these accesses is a write operation without proper synchronization (e.g., without locks). This can lead to unpredictable behavior, crashes, or incorrect program output.
Here is some information about Helgrind.
Helgrind:
- Detects data races, potential deadlocks, and lock-order violations.
- Useful for debugging multi-threaded applications where data consistency is crucial.
Data Race Detection:
If Helgrind detects that two threads are accessing the same memory location concurrently without proper synchronization, and at least one of these accesses is a write, it flags this as a data race.
Please have a look at my video - it's all explained here.
//============================================================================
// Name : CyclicDependencyDeadLock.cpp
// Author : Som
// Version :
// Copyright : som-itsolutions
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
std::mutex lock1, lock2;
void threadA() {
int count = 0;
std::lock_guard<std::mutex> guard1(lock1);
for (int i = 0; i<100000; i++){
count++;
}
std::lock_guard<std::mutex> guard2(lock2);
//cout<<"Thread id " <<this_thread::get_id()<<" this is okay now because of correct lock order " <<count<<endl;
cout<<"Thread id " <<this_thread::get_id()<< " this will never be printed..."<<count<<endl;
}
void threadB() {
std::lock_guard<std::mutex> guard2(lock2);
int count = 0;
for (int i = 0; i<100000; i++){
count++;
}
std::lock_guard<std::mutex> guard1(lock1);
//cout<<"Thread id " <<this_thread::get_id()<<" this is okay now because of correct lock order " <<count<<endl;
cout<<"Thread id " <<this_thread::get_id()<< " this will never be printed..."<<count<<endl;
}
int main() {
std::thread t1(threadA);
std::thread t2(threadB);
t1.join();
t2.join();
return 0;
}
No comments:
Post a Comment