This program generates prime numbers using the same algorithm as my
Prime Number Generator - Pipes
program. However, instead of sending data to other processes through pipes, this program
demonstrates communication between threads by sharing access to the same memory.
In particular, each thread shares access with another thread to a deque container class. Access
to the deques is secured through the use of POSIX mutexes, and every read and write operation done
to the deque is wrapped in error-checking "read" and "write" functions.
void WriteDeque(deque<int> &p, pthread_mutex_t &mutex, pthread_cond_t &condition, int temp)
{
int rc = pthread_mutex_lock(&mutex); //secure mutex
ErrorCheck(rc); //error checking for mutex locking
p.push_back(temp); //adds int to the deque
rc = pthread_mutex_unlock(&mutex); //unlocks mutex
ErrorCheck(rc);
rc = pthread_cond_signal(&condition); //signals a write has taken placE
ErrorCheck(rc);
}
void ErrorCheck(int x)
{
if (x != 0)
{
cerr << "MAJOR ERROR" << endl;
exit(-1);
}
}
|
"Write" function WriteDeque and the error-checking function