I have a project in my C++ class that I've been having some trouble with. I don't fully understand semaphores, and this particular problem revolves around semaphores. The given code is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
// project4.cpp : main project file.
#include "stdafx.h"
using namespace System;
using namespace System::Threading;
ref class PrintTasks
{
private:
static Semaphore ^canPrintA = gcnew Semaphore(1, 1);
static Semaphore ^canPrintB = gcnew Semaphore(0, 1);
static Semaphore ^canPrintC = gcnew Semaphore(0, 1);
public: static bool runFlag = true;
public:
void PrintA(Object^ name) {
while (runFlag) {
canPrintA->WaitOne();
Console::Write("{0}\n", "A");
canPrintB->Release();
}
}
void PrintB(Object^ name) {
while (runFlag) {
canPrintB->WaitOne();
Console::Write("{0}\n", "B");
canPrintC->Release();
}
}
void PrintC(Object^ name) {
while (runFlag) {
canPrintC->WaitOne();
Console::Write("{0}\n", "C");
canPrintA->Release();
}
}
};
int main(array<System::String ^> ^args)
{
PrintTasks ^tasks = gcnew PrintTasks();
// First Method
Thread ^thread1 = gcnew Thread ( gcnew ParameterizedThreadStart( tasks, &PrintTasks::PrintA ) );
Thread ^thread2 = gcnew Thread ( gcnew ParameterizedThreadStart( tasks, &PrintTasks::PrintB ) );
Thread ^thread3 = gcnew Thread ( gcnew ParameterizedThreadStart( tasks, &PrintTasks::PrintC ) );
thread1->Start("printA");
thread2->Start("printB");
thread3->Start("printC");
Thread::Sleep(50);
PrintTasks::runFlag=false;
thread3->Abort();
thread2->Abort();
thread1->Abort();
return 0;
}
|
I have written it so that this will continuously print A on one line, B on the next, C on the next, A, B, C, and so on. The goal is to write ONLY semaphore-related statements (no control structure, no added print statements, no nothing) to print AAA on one line, BB on the next, and C on the next, for the pattern AAA, BB, C, AAA, BB, C, AAA, BB, C. Any suggestions on how to make the A part print three times and the B part twice, by only adding/deleting/editing semaphore stuff?