Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

If two processes use a pipe to exchange a large amount of data on a multi-proces

ID: 3844815 • Letter: I

Question

If two processes use a pipe to exchange a large amount of data on a multi-processor system, the communication should be faster if the processes run on the same CPU than if they run on different CPUs. The reason is that when the two processes runon the same CPU, the pipe data will be more quickly accessed because it can remain in that CPU’s cache. By contrast, when the processes run on separate CPUs,the benefits of the CPU cache are lost.

Think about a potential test case that can be used to demonstrate this behavior. Provide a simple C++ for your test program. (HINT: investigate the Linux sched_setaffinity() system call).

**Edit: That is how the question was asked on homework. My interpretation of it is to write a small C++ program that uses sched_setaffinity() and demonstrate how two processes on the same processor (CPU) will run faster than using parallel programming (threaded, fork(), etc).

Explanation / Answer

#include <stdio.h>
#include <stdlib.h>
//#define __USE_GNU
#include <sched.h>
#include <errno.h>
#include <unistd.h>
#include <iostream>
using namespace std;

#define printError(en, msg) do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)


int main(int argc, char *argv[]) {

const int codeId = 1;
const pid_t pid = getpid();

cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(codeId, &cpuset);

const int set_result = sched_setaffinity(pid, sizeof(cpu_set_t), &cpuset);
if (set_result != 0) {

    printError(set_result, "sched_setaffinity");
}

const int get_affinity = sched_getaffinity(pid, sizeof(cpu_set_t), &cpuset);
if (get_affinity != 0) {

    printError(get_affinity, "sched_getaffinity");
}

if (CPU_ISSET(codeId, &cpuset)) {

    cout <<"Process created =" << pid << "on affinity CPU "<<codeId << endl;
} else {

    cout << "Error to set process = "<<pid <<"on affinity CPU "<<codeId <<endl;
}

return 0;
}