I’m currently completing an assignment that involves using multithreading and multiprocess programming for the absolute first time. I seem to have stumbled through multiprocess programming and accidentally increased performance by around ~20% but I can’t tell you that I understand it. Unfortunately I haven’t even gotten lucky enough to figure out pthreads completely yet, and I am almost at a loss as to how this actually works. Without further ado, here is the code I’m trying to split correctly.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <errno.h>
#include <sys/time.h>
#define DATASIZE (4<<20)
int main()
{
double A[200][200];
double B[200][200];
double C[200][200];
int i, j, k, m;
int outfile, result, count;
unsigned seed;
struct timeval before, after;
char *buff;
buff = (char *)malloc(sizeof(char)*(16<<20));
srandom(seed);
for (i=0; i<200; i++)
for (j=0; j<200; j++) {
A[i][j] = random()/100.0;
B[i][j] = random()/100.0;
}
gettimeofday(&before, NULL);
for (m=0 ; m < 100; m++) {
/* Computation */
/* This is what we're trying to split into one thread*/
for (i=0; i<200; i++)
for (j=0; j<200; j++) {
C[i][j] = 0;
for (k=0; k<200; k++)
C[i][j] += A[i][k]*B[k][j];
}
/* I/O */
/*And this is what we'll put in the other thread*/
outfile = open("testfile", O_RDWR|O_CREAT|O_APPEND, 0777);
if (outfile <= 0)
perror("Error opening file\n");
else {
result = write(outfile, buff, DATASIZE);
if (result <= 0)
perror("Error writing file\n");
}
close(outfile);
}
free(buff);
gettimeofday(&after, NULL);
count = (after.tv_sec - before.tv_sec) * 1e6;
count += (after.tv_usec - before.tv_usec);
printf("Total time for single process in usec: %d\n", count);
return 0;
};
From the few unhelpful examples I’ve gleamed from the internet, they show splitting these two things into external functions outside the main function. Then I’d have to pass them into pthread_create like so:
/*I would declare the pthread_t* vars higher in the code*/
pthread_create(pthread_t* first,NULL,/*function name*/,NULL);
pthread_create(pthread_t* second,NULL,/*second function name*/,NULL);
pthread_join(pthread_t* first,NULL);
pthread_join(pthread_t* second,NULL);
Is it really this “simple”? Am I required to create new external functions or can I somehow keep them in main and use pthread? Am I missing some important part of understanding how pthread works and how to use it in the future?
Am I required to create new external functions or can I somehow keep them in main and use pthread?
Yes, pthread_create() creates new thread within the calling process that starts execution by invoking start_routine() specified by 3. argument of this function:
void *(*start_routine) (void *).Is it really this “simple”?
Yes, it is.