Concerning programm semaphore.cpp (program see below) If we change Line #31 as f
ID: 3903193 • Letter: C
Question
Concerning programm semaphore.cpp (program see below)
If we change Line #31 as follows :
... nSemaphoreCount = 3
What will happen with the output? Why?
---------------------
semaphore.cpp
#include <iostream>
#include <pthread.h> //POSIX thread header
#include <unistd.h> //UNIX standard header
#include <semaphore.h>
using namespace std;
sem_t g_semt; //semaphore
void
*fn_work_thread(void *p)
{
pthread_t tID = pthread_self(); //obtain ID of the calling thread
cout << "**********Thread " << tID << " is waiting for a semaphore**********" << endl;
sem_wait(&g_semt); //decrements the semaphore pointed by g_semt;
cout << "----------Thread " << tID << " got a semaphore, is running----------" << endl;
usleep(1000 * 1000 * 2); //sleep the calling thread, for 2 seconds
sem_post(&g_semt); //unlock the semaphore, i.e., increase g_semt with 1
const char* pRet[] = { "thread finished!" };
return pRet;
}
int
main(void)
{
const size_t nThreadCount = 5; //there are totally 5 threads
//line 31// const unsigned int nSemaphoreCount = 2; //initial value of semaphore
int nRet = -1;
void *pRet = NULL;
pthread_t threadIDs[nThreadCount] = { 0 };
nRet = sem_init(&g_semt, 0, nSemaphoreCount); //initialize semaphore, here g_semt is set as 2
if (nRet != 0)
return -1;
//start new threads
for (size_t i = 0; i < nThreadCount; ++i)
{
//create new threads
nRet = pthread_create(&threadIDs[i], NULL, fn_work_thread, NULL);
if (nRet != 0)
{
cout << "Fail to start new thread: " << i << endl;
continue;
}
}
for (size_t i = 0; i < nThreadCount; ++i)
{
int nRet2 = pthread_join(threadIDs[i], &pRet); //wait for a child thread to terminate
// cout << "Thread " << threadIDs[i] << " return value is: " << (char*)pRet << endl;
}
cout << endl;
sem_destroy(&g_semt); //destroy semaphore
return 0;
}
Explanation / Answer
If we change nSemaphoreCount as 3 then the output will be
cout<<"----------Thread " << tID << " got a semaphore, is running----------" will be printed 3 times as 3 threads will get semaphore access instead of 2 in the case where nSemaphoreCount was 2.
With each thread access the semaphore will get decremented
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.