Prime Number Generator using Threads

Program Description

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.

Code Snippet

 
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

Features

Sample Run

 
kevin@LightningJoe:~/public_html/portfolio/png-threads$ ./png-threads 75

Known Prime: 3
Known Prime: 5
Known Prime: 7
Known Prime: 11
Known Prime: 13
Known Prime: 17
Prime: 19
Prime: 23
Prime: 29
Prime: 31
Prime: 37
Prime: 41
Prime: 43
Prime: 47
Prime: 53
Prime: 59
Prime: 61
Prime: 67
Prime: 71
Prime: 73