CPP 059 – Dead Lock & Live Lock

Table of Contents

Dead Lock

A devam edebilmek için B ye, B de devam edebilmek için doğrudan ya da dolayı yoldan A ya ihtiyacı varsa bu bir dead lock oluyor.

#include <iostream>
#include <vector>
#include <thread>
#include <mutex>

using namespace std;

mutex m1, m2;

void f1() {
	unique_lock ul1(m1);
	// Do some work with m1
	this_thread::sleep_for(chrono::milliseconds(100));
	unique_lock ul2(m2);
}
void f2() {
	unique_lock ul2(m2);
	// Do some work with m2
	this_thread::sleep_for(chrono::milliseconds(100));
	unique_lock ul1(m1);
}
int main() {
	thread t1(f1);
	thread t2(f2);

	t1.join();
	t2.join();
	cout << "Hello World!" << endl;

}

Live Lock

Live lock da tıpkı deadlock gibidir ama halen işlemin devam ettiğine dair bir hayat belirtisi vardır:

#include <iostream>
#include <thread>
#include <mutex>

using namespace std;

timed_mutex m1, m2;

void f1() {
	unique_lock l1(m1);
	unique_lock l2(m2, defer_lock);

	this_thread::sleep_for(500ms); // Simulate some work

	while (!l2.try_lock_for(1000ms))
		cout << "A: You first\n";	
}
void f2() {
	unique_lock l1(m1, defer_lock);
	unique_lock l2(m2);

	this_thread::sleep_for(500ms); // Simulate some work

	while (!l1.try_lock_for(1000ms))
		cout << "B: After you\n";
}
int main() {
	cout << "Two kind man stay in front of a door..." << endl;
	thread t1(f1);
	this_thread::sleep_for(400ms); // Simulate some work
	thread t2(f2);

	t1.join();
	t2.join();

	cout << "and they continue..." << endl;
	return 0;

}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *