Advertisement
Thiff

Zitra

Nov 6th, 2017
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <iostream>
  5. #include <sys/time.h>
  6. #include <sys/param.h>
  7. #include <pthread.h>
  8. #define TYPE int
  9. using namespace std;
  10.  
  11. const int count_Thread = 2;
  12. struct thread_argument
  13. {
  14.     int id;                 // user identification
  15.     int from, length;       // data range
  16.     TYPE *data;
  17. };
  18. int rand32()
  19. {
  20.     return rand() * RAND_MAX + rand();
  21. }
  22. void fill_array(TYPE *arr, int start, int end)
  23. {
  24.     for (int i = start; i < end; i++)
  25.     {
  26.         arr[i] = rand32() % (end * 10);
  27.     }
  28. }
  29. void *fill_thread( void *void_arg )
  30. {
  31.     thread_argument *ptr_data = ( thread_argument * ) void_arg;
  32.  
  33.     printf( "Thread %d started from %d with length %d...\n",
  34.         ptr_data->id, ptr_data->from, ptr_data->length );
  35.  
  36.     fill_array( ptr_data->data, ptr_data->from, ptr_data->length );
  37.  
  38.     return NULL;
  39. }
  40.  
  41. int main( int na, char **arg )
  42. {   int my_length;
  43.     cin>>my_length;
  44.     TYPE *my_array = new TYPE [ my_length ];
  45.     if ( !my_array )
  46.     {
  47.         printf( "Not enought memory for array!\n" );
  48.         return 1;
  49.     }
  50.  
  51.     pthread_t pt[count_Thread];
  52.     thread_argument ta[count_Thread];
  53.  
  54.     // Initialization of thread arguments
  55.     for (int i = 0; i < count_Thread; i++)
  56.     {                
  57.         ta[i].id = i;                                    
  58.         ta[i].from = i * (my_length/count_Thread);                      
  59.         ta[i].to = ta[i].from + (my_length/count_Thread);
  60.         ta[i].data = my_array;        
  61.     }
  62.  
  63.     for (int i = 0; i < count_Thread; i++)
  64.     {    
  65.         pthread_create( &pt[i], NULL, fill_thread, &ta[i] );  
  66.     }
  67.     for (int i = 0; i < count_Thread; i++)
  68.     {
  69.         pthread_join( pt[i], NULL );        
  70.     }
  71.    
  72.     for(int i = 0; i < my_length;i++)
  73.     {
  74.        cout>>(my_array[i]);
  75.     }
  76.    
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement