Today I have to make my algorithm running in parallel into order to make it faster. At the 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 OK, however, there ' no way to change the ' shared ' variables into child processes. Because each child process has a 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<sizeof (PT); i++) {printf ("%02x", (unsigned) (ptc[i));
} void* Gen_gpd_num (void* arg) {struct Thread_info *tinfo = (struct thread_info *) arg;
Do something pthread_exit (0);
int main () {unsigned int tnum = 20;
Double incr= (double) n/(double) tnum;
thread_info* Tinfo=new Thread_info[tnum];
int err;
void* Res; /* Start children. * for (unsigned int idx=0;idx<tnum; ++idx) {tinfo[idx].start=incr*idx;
tinfo[idx].end=incr* (idx+1);
Tinfo[idx].gpdarr=gpdnum; TINFO[IDX].
g=g; TINFO[IDX].
L=l;
TINFO[IDX].L1=L1;
TINFO[IDX].L2=L2; TINFO[IDX].
M=m;
Err = Pthread_create (&tinfo[idx].thread_id, NULL, &gen_gpd_num, &tinfo[idx]);
if (err!=0) printf ("Can" t create thread: [%s] ", strerror (err));
else Pthread_join (tinfo[idx].thread_id, &res);
} delete [] tinfo; }
The potential problem of using multi-threading in Linux are--it is hard to figure out if there really are many threads ar e running simultaneously.
When compiling multi-threading the program using GCC, the Pthread library must be specified:
g++-O foo-wall foo.cc-l/usr/lib-lpthread
References:
How to Create Threads in Linux (with a C Example program) http://www.kernel.org/doc/man-pages/online/pages/man3 /pthread_create.3.html