In this task, you are required to implement methods in the given file mutex.cpp
ID: 3883637 • Letter: I
Question
In this task, you are required to implement methods in the given file mutex.cpp You may use the previous tasks code for this. Your need to implement these using threads, you may use high level C++ threads or pthreads for this. Things to note: 1. You may NOT modify the function threadFunction in this task verv time the program executes the contents of the file sho 3. The file that you write data to should be called "mutex.txt 4. In this task there is an exception thrown in the threadFunction0 you need to find a way to overcome this and unlock successfully in order to avoid the deadlock without editing the threadFunctionExplanation / Answer
#include <iostream>
#include <unistd.h>
#include <fstream>
#include <pthread.h>
#include <thread>
#include <cstdlib>
using namespace std;
bool isBusy = false;
void writeToFile(int threadNumber)
{
ofstream outputFile;
outputFile.open("dead-lock.txt");
outputFile << "[" << threadNumber;
for (int a=2; a<=10; a++)
outputFile << ", " << threadNumber*a;
outputFile << "] ";
}
void lock()
{
isBusy = true;
}
void unlock()
{
isBusy = false;
}
void threadFunction(int threadNumber)
{
int x = 0;
int y = 0;
try{
lock();
writeToFile(threadNumber);
throw new exception();
unlock();
}
catch(...){
cout << "Something went wrong!" << endl;
}
}
int main (int argc, char const *argv[])
{
int numThreads = 0;
if (argc==2)
numThreads = atoi(argv[1]);
else
exit(EXIT_FAILURE);
thread **threads = new thread*[numThreads];
for (int a=0; a<numThreads; a++)
{
threads[a] = new thread(threadFunction, a+1);
cout << "Created thread: " << threads[a]->get_id() << endl;
}
for (int a=0; a<numThreads; a++)
{
cout << threads[a]->get_id() << endl;
if (threads[a]->joinable())
threads[a]->join();
else
{
cout << "Error occured ";
exit(EXIT_FAILURE);
}
}
for (int a=0; a<numThreads; a++)
delete threads[a];
delete [] threads;
thread thread1(threadFunction, 1), thread2(threadFunction, 2);
cout << "Created thread: " << thread1.get_id() << endl;
cout << "Created thread: " << thread2.get_id() << endl;
thread1.join();
thread2.join();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.