HP-MPI User's Guide (11th Edition)
Example applications
thread_safe.c
Appendix A264
thread_safe.c
In this C example, N clients loop MAX_WORK times. As part of a single
work item, a client must request service from one of Nservers at random.
Each server keeps a count of the requests handled and prints a log of the
requests to stdout. Once all the clients are done working, the servers are
shutdown.
#include <stdio.h>
#include <mpi.h>
#include <pthread.h>
#define MAX_WORK 40
#define SERVER_TAG 88
#define CLIENT_TAG 99
#define REQ_SHUTDOWN -1
static int service_cnt = 0;
int process_request(request)
int request;
{
if (request != REQ_SHUTDOWN) service_cnt++;
return request;
}
void* server(args)
void *args;
{
int rank, request;
MPI_Status status;
rank = *((int*)args);
while (1) {
MPI_Recv(&request, 1, MPI_INT, MPI_ANY_SOURCE,
SERVER_TAG, MPI_COMM_WORLD, &status);
if (process_request(request) == REQ_SHUTDOWN)
break;
MPI_Send(&rank, 1, MPI_INT,
status.MPI_SOURCE,
CLIENT_TAG, MPI_COMM_WORLD);
printf("server [%d]: processed request %d for
client %d\n",
rank, request, status.MPI_SOURCE);
}
printf("server [%d]: total service requests: %d\n", rank,
service_cnt);