Home > Articles > Programming > General Programming/Other Languages

📄 Contents

  1. Introduction
  2. How Does the PVM Library Work?
  3. Simplifying Access Through Interface Classes
Like this article? We recommend

Simplifying Access Through Interface Classes

While the PVM library is powerful and straightforward to use, the message-passing protocol can be a bit tedious. Before a data element can be sent, it must be packed. Before a data element can be received, it must be unpacked. pvm_pk and pvm_upk routines are available for most of the built-in datatypes, as shown in the following table.

Pack Routine

Unpack Routine

pvm_pkbyte()

pvm_upkbyte()

pvm_pkdouble()

pvm_upkdouble()

pvm_pkfloat()

pvm_upkfloat()

pvm_pkint()

pvm_upkint()

pvm_pklong()

pvm_upklong()

pvm_pkshort()

pvm_upkshort()

pvm_pkstr()

pvm_upkstr()


The appropriate pvm_pk and pvm_upk routines are called and then a pvm_send() or pvm_recv() can be called. The pvm_send() process requires the send buffer to be initialized, which means that pvm_initsend() is called prior to any pvm_pk routines. This process becomes even more demanding when user-defined types need to be passed between PVM processes.

We want to simplify the PVM send-and-receive process by adapting it to the C++ stream metaphor of I/O. Further, we want to take advantage of the C++ information-hiding and encapsulation facilities to shield us from some of the PVM library syntax and to provide a more familiar interface for message passing and error handling. Molding the interface to the PVM routines will make using the PVM library easier and will help to clarify the logic of our parallel programs. As is often the case, the encapsulation and interface adaptation process requires more work up front, but the payoff is immediate and long-lasting. The supplier of the class does the heavy lifting, and the user of the class reaps the immediate benefits. Let's get started.

Listing 1 has two simple PVM programs: Sending Worker sends an integer and a char array, and Receiving Worker receives the integer and char array.

Listing 1 Two simple PVM programs: a sending worker and a receiving worker.

// Sending Worker

#include "pvm3.h"
#include <string.h>
#include <iostream>


int main(int argc,char *argv[])
{
  int NumTasks = 1;
  int Tid,Workers,MTag,Size,Value1;
  char Value2[100];
  long Result;
  Workers = pvm_spawn("worker",NULL,PvmTaskDefault,NULL,NumTasks,&Tid);
  if(Workers == NumTasks){
   MTag = 1;
   strcpy(Value2,"cluster application");
   pvm_initsend(PvmDataDefault);
   Size = strlen(Value2);
   pvm_pkint(&Size,1,1);
   pvm_send(Tid,MTag);
   pvm_initsend(PvmDataDefault);
   pvm_pkstr(Value2);
   pvm_send(Tid,MTag);
   pvm_recv(Tid,MTag);
   pvm_upklong(&Result,1,1);
 }
 else{
     cerr << "Some Appropriate Error Message" << endl;

 }
 pvm_exit();
 return(Workers);

}

// Receiving Worker

#include "pvm3.h"
#include <string.h>
#include <iostream>


int main(int argc,char *argv[])
{
  int NumTasks = 1;
  int Pid,MTag,Value1;
  char Value2[100];
  long RandomNum;
  Pid = pvm_parent();
  MTag = 1;
  strcpy(Value2,"");
  pvm_recv(Pid,MTag);
  pvm_upkint(&Value1,1,1);
  pvm_recv(Pid,MTag);
  pvm_upkstr(Value2);
  // do some stuff
  RandomNum = 981928191;
  pvm_initsend(PvmDataDefault);
  pvm_pklong(&RandomNum,1,1);
  pvm_send(Pid,MTag);
  pvm_exit();
  return(0);

}

Notice the pvm_pk and pvm_upk routines. These would be required for every datatype involved in a send or receive operation. Each datatype that's sent or received by a PVM program has its own set of pack and unpack functions. Also notice the use of the pvm_initsend() routine. This routine is required before most send operations. As the number and type of data elements involved in send and receive operations increases, the tedium sets in. Also, we're far removed from our familiar iostream metaphor. We can transform this situation by providing interface classes to the PVM routines. We have several goals:

  • The interface class hides one interface while providing another (more convenient or appropriate) interface. In this case, we want to adapt the pvm_initsend(), pvm_pk, pvm_upk, pvm_send(), and pvm_recv() interfaces to the more familiar C++ iostream interface. Once these interfaces are adapted, we can concentrate more on the challenges of parallel and distributed programming without being bogged down by the syntax of the PVM library.

  • Further, if we design and implement an interface class that's consistent with the familiar istream and ostream interfaces, we remove the learning curve for other developers who are involved in our project or who might use our interface class. To pull off this switcheroo, our interface class must provide definitions for all of the datatypes that the PVM routines handle.

  • Finally, we should make the class easy to use with user-defined types.

Listing 2 shows skeleton class declarations for ipvm_stream and opvm_stream classes.

Listing 2 Skeleton class declarations for ipvm_stream and opvm_stream.

class ipvm_stream{
public:
  ipvm_stream(int Tid, int Mid);
  void taskId(int Tid);
  void messageId(int Mid);
  void reset(void);
  ipvm_stream(void);
  ipvm_stream &operator>>(int &Data);
  ipvm_stream &operator>>(string &Data);
  ipvm_stream &operator>>(vector<string> &X);
  ipvm_stream &operator>>(list<string> &X);
  ipvm_stream &operator>>(analysis &X);
  ...
private:
  int TaskId;
  int MessageId;

};

class opvm_stream{
public:
  opvm_stream(void);
  opvm_stream(int Tid, int Mid);
  void taskId(int Tid);
  void messageId(int Mid);
  void reset(void);
  opvm_stream &operator<<(string Data);
  opvm_stream &operator<<(int &Data);
  opvm_stream &operator<<(vector<string> &X);
  opvm_stream &operator<<(list<string> &X);
  opvm_stream &operator<<(analysis &X);
private:
  int TaskId;
  int MessageId;
  ...
};

The proper design and implementation of these classes will require more work up front, but the resulting code is considerably simplified, easier to understand, and easier to maintain. The ipvm_stream and opvm_stream classes are scaled-down versions of what we use. Keep in mind that these classes wouldn't be complete without an error-handling and exception-handling policy. Also, because we're using them in a parallel programming environment, there are opportunities for data race; therefore, locking and synchronization policies come into play. The ipvm_stream and opvm_stream classes don't inherit any of the istream or ostream family of classes; instead, they define a similar interface. So, while the ipvm_stream and opvm_stream classes are not related by inheritance, they are related by interface. The ipvm_stream class is used for receiving objects from other PVM workers, and the opvm_stream class is used to send objects to other PVM workers.

Listing 3 shows some skeleton definitions for these classes. Notice that buffers involved and PVM functional requirements must be met by data members that are defined by the ipvm_stream and opvm_stream classes.

Listing 3 Definitions of class methods for ipvm_stream and opvm_stream.

void ipvm_stream::reset(void)
{
  pvm_initsend(PvmDataDefault);


}

ipvm_stream::ipvm_stream(int Tid, int Mid)
{
  ...
  TaskId = Tid;
  MessageId = Mid;
}

ipvm_stream &ipvm_stream::operator>>(string &Data)
{

  ...
  char Buffer[2048];
  pvm_recv(TaskId,MessageId);
  pvm_upkstr(Buffer);
  Data.assign(Buffer);
  return(*this);

}

ipvm_stream &ipvm_stream::operator>>(int &Data)
{

  pvm_recv(TaskId,MessageId);
  pvm_upkint(&Data,1,1);
  return(*this);

}



ipvm_stream &ipvm_stream::operator>>(vector<string> &X)
{
  ...
  char Buffer[2048];
  int NumWords;
  string Data;
  pvm_recv(TaskId,MessageId);
  pvm_upkint(&NumWords,1,1);
  int N;
  for(N = 0;N < NumWords; N++)
  {
    pvm_upkstr(Buffer);
    Data.assign(Buffer);
    X.push_back(Data);
  }
  return(*this);

}



opvm_stream &opvm_stream::operator<<(string Data)
{

  reset();
  pvm_pkstr(const_cast<char *>(Data.c_str()));
  pvm_send(TaskId,MessageId);
  return(*this);

}

opvm_stream &opvm_stream::operator<<(int &Data)
{
  reset();
  pvm_pkint(&Data,1,1);
  pvm_send(TaskId,MessageId);
  return(*this);

}

opvm_stream &opvm_stream::operator<<(vector<string> &X)
{
  ...
  reset();
  int N = 0;
  for(N = 0;N < X.size(); N++)
  {
    reset();
    pvm_pkstr(const_cast<char*>(X[N].c_str()));
    pvm_send(TaskId,MessageId);
  }
  return(*this);


}

opvm_stream &opvm_stream::operator<<(list<string> &X)
{

  ...
  reset();
  string Token;
  while(X.size() > 0)
  {
    Token.assign(X.front());
    X.pop_front();
    pvm_pkstr(const_cast<char*>(Token.c_str()));
    pvm_send(TaskId,MessageId);
  }
  ...

}

Notice that the ipvm_stream and opvm_stream methods simply wrap the pvm_pk, pvm_upk, pvm_send(), pvm_recv(), and pvm_initsend() routines. This is why interface classes are sometimes referred to as wrapper classes. Our interface to the PVM routines is now complete. Listing 4 is a rewrite of the program in Listing 1.

Listing 4 Listing 1 rewritten to use the ipvm_stream and opvm_stream classes.

// Sending Worker

#include "pvm3.h"
#include <string>
#include <iostream>
#include "pvm_stream.h"

int main(int argc,char *argv[])
{
  int NumTasks = 1;
  int Tid,Workers,MTag,Size,Value1;
  string Value2("cluster application");
  long Result;
  Workers = pvm_spawn("worker",NULL,PvmTaskDefault,NULL,NumTasks,&Tid);
  if(Workers == NumTasks){
   MTag = 1;
   opvm_stream Destination(Tid,MTag);
   ipvm_stream Source(Tid,MTag);
   Size = Value2.size();
   Destination << Size << Value2.c_str();
   Source >> Result;
  }
  else{
     cerr << "Some Appropriate Error Message" << endl;

  }
  pvm_exit();
  return(Workers);

}


// Receiving Worker

#include "pvm3.h"
#include <string.h>
#include <iostream>
#include "pvm_stream.h"

int main(int argc,char *argv[])
{
  int NumTasks = 1;
  int Pid,MTag,Value1;
  string Value2;
  long RandomNum;
  Pid = pvm_parent();
  MTag = 1;
  opvm_stream Destination(Pid,MTag);
  ipvm_stream Source(Pid,MTag);
  Source >> Value1 >> Value2;
  // do some stuff
  RandomNum = 981928191;
  Destination << RandomNum;
  pvm_exit();
  return(0);

}

The PVM program in Listing 4 uses our iostream metaphor and hides the details of the PVM send-and-receive process. The sender can be on any computer in the virtual machine, and the receiver can be on any computer in the virtual machine, and this code will work.

We reap even greater benefits when we send complex user-defined datatypes between PVM processes. For instance, at Ctest Labs, we've developed a cluster-based text-file analysis utility that takes advantage of the multiple processors in a cluster environment. The utility is used to perform detailed content analysis of text files in real time. The utility is given hundreds—possibly thousands—of text files to analyze, and it must return the analysis in a relatively short period of time. Because the analysis involves set manipulations, transformations of some text elements to horn clause form, skolemization (another type of transformation), and graph-traversal techniques, this utility is processor-intensive, and the more processors available, the better the utility performs. Using this utility, we routinely send and receive to and from pvmd's deques, multisets, lists, and vectors of built-in types and user-defined objects using our ipvm_stream and opvm_stream classes. Listing 5 shows the implementation of the inserter that's used to insert a vector of strings into an opvm_stream.

Listing 5 Inserts a vector of strings into the opvm_stream.

opvm_stream &opvm_stream::operator<<(vector<string> &X)
{
   ...
   reset();
   int N = 0;
   for(N = 0;N < X.size(); N++)
   {
    reset();
   pvm_pkstr(const_cast<char*>(X[N].c_str()));
   pvm_send(TaskId,MessageId);
   }
   ...
   return(*this);


}

Keep in mind that the inserter defined in Listing 5 is responsible for setting an error state of the pvm_stream, throwing an exception, or both. Our text-based analysis utility relies on custom-designed error classes in most cases, and on exception-handling techniques in the case of extreme failure. We have developed our text-based analysis utility for the PVM and the MPI environment, with ipvm_stream, impi_stream, opvm_stream, and ompi_stream interface classes. In the second article of this three-part series, we'll take a closer look at the implementation of the pvm_stream and mpi_stream classes and how they're used in the context of this cluster-based text-file analysis utility.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020