Basic Linux Multi-Process & Multi-Thread Programming

Today I have to make my algorithm running in parallel in order to make it faster. At first I used following way to implement multi-process:

	unsigned int proc_num = 5;
	pid_t* pids=new pid_t[proc_num];
	double incr=(double)N/(double)proc_num;
	
	/* Start children. */
	for (unsigned int i = 0; i < proc_num; ++i) {
		if ((pids[i] = fork()) < 0) {
	    		perror("fork");
	    		abort();
	 	} else if (pids[i] == 0) {
	    		// DoWorkInChild();

	    		exit(0);
	  	}
	}
	
	/* Wait for children to exit. */
	int status;
	pid_t pid;
	while (proc_num > 0) {
	  	pid = wait(&status);
		if(status != 0)
	  		printf("Child Process with PID %ld aborted with status 0x%x.\n", (long)pid, status);
	  	--proc_num;  // TODO(pts): Remove pid from the pids array.
	}

Above way worked well, however, there's no way to change the "shared" variables in child processes. Because each child process has an independent copy of all variables.

In order to change the same array in parallel, I implemented multi threads.

struct thread_info {    /* Used as argument to thread_start() */
	pthread_t thread_id;        /* ID returned by pthread_create() */
	int	start;       /* Application-defined thread # */
	int     end;      /* From command-line argument */
	int*	gpdarr;	/* Array to store GPD number */
	long int G;	/* genome length */
	unsigned int L;	/* read length */
	double l1;	// GPD parameter lambda1
	double l2;	// GPD parameter lambda2
	double M;	// maximum of GPD density
};

void printPt(pthread_t pt) {
  unsigned char *ptc = (unsigned char*)(void*)(&pt);
  printf("0x");
  for (size_t i=0; i

The potential problem of using multi-threading in Linux is -- it is hard to figure out if there really are many threads are running simultaneously. 

When compiling multi-threading program using GCC, pthread library must be specified:

g++ -o foo -Wall foo.cc -L/usr/lib -lpthread

References:

  1. How to Create Threads in Linux (With a C Example Program)

  2. http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_create.3.html


你可能感兴趣的:(C/C++,Unix/Linux)