Posted By: Drs (Fortran je muj kamarad) on 'CZprogram'
Title: Re: posix threads *^*&%*$*
Date: Mon Sep 24 12:21:50 2001
> Dik za kazde info, kdybyste nekdo zverejnili kratky programek, ktery chodi,
> budu neskonale vzdecny.
Cau !
Drive jsem neco s pthready delal, takze jsem z jednoho programu vykuchal
relevantni cast a hazim ji sem. Puvodne to byla cast kodu, ktery bezel na
linuxovem clusteru a mezi nody komunikoval pomoci MPI, takze jsou tam jiste
neobratnosti v syntaxi, ktere tam zustaly, kdyz jsem ted tohle MPI vyhazel.
To je souveti :-))
Toz tady je:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <pthread.h>
double f(double x)
{
double y;
y=x + sin(x);
return y;
}
double solution=0.0; /* integral*/
double mya; /* beginning of my interval */
double myb; /* end of my interval */
double myd; /* step */
double d; /* length of interval*/
pthread_mutex_t mut;
void *slave()
{
double x;
double pomssol=0.0;
for (x=mya; x<mya+d/2.0; x=x+myd) /*integration over the 2nd half of int. */
{
pomssol=pomssol+0.5*(f(x)+f(x+myd))*myd;
}
pthread_mutex_lock(&mut); /* becouse changing global variable */
solution=solution+pomssol; /* returning result */
pthread_mutex_unlock(&mut);
return;
}
int main(int argc, char **argv)
{
FILE *outp;
double PI=3.141592654;
double a=0.0; /* left border */
double b=PI; /* right border */
double pomsol=0.0;
double x; /* point in which I compute the value */
pthread_t thread;
d=(b-a);
myd=1.0e-7;
/* and sends it to all processes */
mya=a; /* compute borders of my interval */
myb=b;
pthread_mutex_init(&mut,NULL);
if (pthread_create(&thread,NULL,slave,NULL) != 0)
perror("Pthread create failed !!!");
for (x=mya+d/2.0; x<myb; x=x+myd) /* comp. of integral over part of (a,b) */
{
pomsol=pomsol + 0.5*(f(x)+f(x+myd))*myd;
}
pthread_mutex_lock(&mut); /* slave may write now too */
solution=solution+pomsol; /* total result of this node */
pthread_mutex_unlock(&mut);
if (pthread_join(thread,NULL) != 0)
perror("Pthread join failed !!!");
if ((outp = fopen("outp","w")) == NULL)
{ printf("Error open file !!!"); exit; };
fprintf(outp,"Integral of the function from a to b is %f.n",solution);
printf("Integral of the function from a to b is %f.n",solution);
fclose(outp);
}
Ted jsem to zkousel prekladat na Linuxu RH 6.2 CZ, v pohode beha a funguje.
Prekladal jsem to bezne gcc -O -lpthread -o pthr pthready.c
Treba to pomuze.
Tak a ted bud neskonale vdecny :-)
DrS
------------------------------------------------------------------
To jen aby rec nestala ...