Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In this task, you are required to implement methods in the given file deadlock.c

ID: 3883634 • Letter: I

Question

In this task, you are required to implement methods in the given file deadlock.cpp Your need to implement these using threads, you may use high level C++ threads or pthreads for this purpose Methods to implement are defined below 1. writeToFile(int threadNumber) - this simply writes data to a file called "dead lock.txt", the data that must be written consists of the following The first 10 iterations of the product of the thread number and i separated by a single space - Where i is a loop variable from 1 to 10 Example: if thread number is 2 the data that should be written to the file is: [ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 2. lock) - implement any type of locking mechanism of your choice. You may use a 3. unlock - implement a unlocking mechanism with relation to the way you imple- 4. main(...) - You should have one command line argument that accepts the number library for this mented the lock() function. of threads to create - For each thread created you need to display a message as well as the thread ID Your threads should call the threadFunction() function

Explanation / Answer

#include <thread>
#include <iostream>
#include <cstdlib>
#include <mutex>
#include <fstream>

using namespace std;

mutex mtx;

int flag=0;

void writeToFile(int threadNumber)
{
ofstream myfile;
myfile.open("dead-lock.txt");
int i;
for(i=1;i<=10;i++)
{
myfile<<i*threadNumber<<",";
}
myfile.close();
}

void lock()
{
mtx.lock();
}

void unlock()
{
mtx.unlock();
}

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 a,i;
a=stoi(argv[0]);
thread arr[a];
for(i=0;i<a;i++)
{
arr[i](threadFunction);
cout<<"Created Thread: "<<arr[i]<<endl;
}
return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote