Advertisement
Guest User

Untitled

a guest
Mar 8th, 2015
368
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.11 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <stdint.h>
  5. #include <inttypes.h>
  6.  
  7. typedef struct neco{
  8.  int *pole;
  9.  int local_konec;
  10.  int64_t soucet;
  11.  pthread_t thr_id;
  12. }STRUCT;
  13.  
  14. void *thrFunc ( void *arg ){
  15.   STRUCT *data = (STRUCT *)arg;
  16.   int *i;
  17.   for (i=data->pole; i!=data->pole + data->local_konec; i++ ){
  18.    data->soucet+=*i;
  19.   }  
  20.  return NULL;
  21. }
  22.  
  23. void napln_pole(int *pole, int velikost){
  24.  int i;
  25.  for(i=0; i<velikost; i++)
  26.    *(pole+i) = i % 10;
  27. }
  28.  
  29. void napln_strukturu(STRUCT *structure, int velikost, int poc_vlaken, int *pole){
  30.  int i, dil;
  31.  dil = velikost / poc_vlaken;
  32.  for(i=0; i<poc_vlaken; i++){
  33.   structure[i].pole = pole+i*dil;
  34.   structure[i].soucet = 0;
  35.   structure[i].local_konec =dil;
  36.  }
  37.  structure[poc_vlaken-1].local_konec += velikost % poc_vlaken;  
  38. }
  39.  
  40. void vypis(int poc_vlaken, STRUCT *structure){
  41.   int64_t soucet;
  42.   int i;
  43.   soucet=0;
  44.   for(i = 0; i<poc_vlaken; i++)
  45.    soucet+=structure[i].soucet;  
  46.   printf("VYSLEDEK%" PRId64 "\n", soucet);
  47. }
  48.  
  49. int main( int argc, char * argv []){
  50.  int velikost, poc_vlaken,i;
  51.  STRUCT *structure;
  52.  pthread_attr_t thrAttr;
  53.  int *pole;
  54.  void *dummy;
  55.  
  56.  if( argc != 3 || sscanf(argv[1], "%d", &velikost) !=1
  57.                || sscanf(argv[2], "%d", &poc_vlaken) !=1){
  58.    printf("Neplatny vstup! Zadej: ./%s pocetPrvku pocetVlaken", argv[0]);
  59.    return 1;
  60.  }
  61.  
  62.  pole = (int*)malloc(velikost*sizeof(*pole));
  63.  structure = (STRUCT*)malloc(poc_vlaken*sizeof(*structure));
  64.  
  65.  
  66.  napln_pole( pole, velikost );
  67.  napln_strukturu(structure, velikost, poc_vlaken, pole);
  68.  
  69.  pthread_attr_init ( &thrAttr );
  70.  pthread_attr_setdetachstate ( &thrAttr, PTHREAD_CREATE_JOINABLE );
  71.  
  72.  for(i=0; i<poc_vlaken; i++)
  73.   if( pthread_create(&structure[i].thr_id, &thrAttr, thrFunc, &structure[i])){
  74.    free ( structure );
  75.    perror ( "Create thread\n" );
  76.    pthread_attr_destroy ( &thrAttr );
  77.    return ( 1 );
  78.   }
  79.   pthread_attr_destroy ( &thrAttr );
  80.  
  81.  
  82.   for ( i = 0; i < poc_vlaken; i ++ )
  83.    pthread_join ( structure[i].thr_id, &dummy );
  84.  
  85.   vypis(poc_vlaken, structure);
  86.  
  87.   free ( structure );
  88. return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement