Jen53403
Programmer
- Jul 17, 2006
- 22
I'm trying to create a simple C++ program that uses fork() to create three processes which work together to calculate the square roots of all integers from 1 - 100. Each thread is supposed to read a common int, print out its root, and increment the int. My problem is I don't know how to get all three processes to share this integer! I tried a pointer, but that didn't help. What can I do?
Below is the code:
Below is the code:
Code:
#include <sys/types.h> // defines pid_t
#include <unistd.h> // defines fork
#include <iostream> // defines cout, cin
#include <stdlib.h> // defines exit()
#include <math.h> // defines sqrt()
using namespace std;
class Process
{
public:
Process() {}
int calcRoots(int* valuePtr);
private:
};
int Process::calcRoots(int* valuePtr)
{
// Get process ID
pid_t id = getpid();
// Calculate
while(*valuePtr <= 100)
{
cout << "P" << id << ":V" << *valuePtr << "=" << sqrt((double)(*valuePtr)) << " ";
if (*valuePtr % 4 == 0)
cout << endl;
*valuePtr += 1;
} // while
exit(0); // do not return
} // calcRoots()
int main()
{
Process child;
int value = 1;
// Create three children to calculate the roots.
if (fork() == 0) // child process
child.calcRoots(&value);
if (fork() == 0) // child process
child.calcRoots(&value);
if (fork() == 0) // child process
child.calcRoots(&value);
} // main()