/[cvs]/joko/Uni/BSArch/04/bmp_fractal.c
ViewVC logotype

Diff of /joko/Uni/BSArch/04/bmp_fractal.c

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.8 by joko, Sat Jul 1 22:10:42 2006 UTC revision 1.16 by joko, Sun Jul 2 12:21:01 2006 UTC
# Line 15  Line 15 
15  #define YSIZE 500  #define YSIZE 500
16  #include "algorithm.h"  #include "algorithm.h"
17    
18    BOOL VERBOSE = FALSE;
19    
20    
21  /* BMP Header */  /* BMP Header */
22  unsigned char header[54]={0x42,0x4d,              // signature BM  unsigned char header[54]={0x42,0x4d,              // signature BM
# Line 47  void printErrorAndExit(const char *msg, Line 49  void printErrorAndExit(const char *msg,
49                                            0,                                            0,
50                                            NULL ))                                            NULL ))
51          {          {
52                  fprintf(stderr,"%s : %s\n",msg,lpMsgBuf);                  fprintf(stderr, "%s: %s\n", msg, lpMsgBuf);
53                  LocalFree(lpMsgBuf);                  LocalFree(lpMsgBuf);
54          }          }
55          else          else
56          {          {
57                  fprintf(stderr,"Error at FormatMesage: %d\n",err=GetLastError());                  fprintf(stderr, "Error at FormatMesage: %d\n",err=GetLastError());
58          }          }
59          exit(err);          exit(err);
60  }  }
# Line 66  void write_blank_file(char *filename) { Line 68  void write_blank_file(char *filename) {
68    // open file handle    // open file handle
69    fd = fopen(filename, "wb+");    fd = fopen(filename, "wb+");
70    if (NULL == fd) {    if (NULL == fd) {
71      perror("open");      perror("Error while opening file for writing");
72      exit(1);      exit(1);
73    }    }
74    
# Line 75  void write_blank_file(char *filename) { Line 77  void write_blank_file(char *filename) {
77        
78    // error checking    // error checking
79    if (-1 == len || len != sizeof(header)) {    if (-1 == len || len != sizeof(header)) {
80      perror("write");      perror("Error while writing header to file");
81      exit(2);      exit(2);
82    }    }
83        
# Line 84  void write_blank_file(char *filename) { Line 86  void write_blank_file(char *filename) {
86    for (i = 0; i < img_size; i++) {    for (i = 0; i < img_size; i++) {
87      len = fwrite("\0\0\0", 1, 3, fd);      len = fwrite("\0\0\0", 1, 3, fd);
88      if (-1 == len || len != 3) {      if (-1 == len || len != 3) {
89        perror("write");        perror("Error while writing data to file");
90        exit(4);        exit(4);
91      }      }
92    }    }
# Line 102  typedef struct _WorkerArguments { Line 104  typedef struct _WorkerArguments {
104  } WORKERARGS, *PWORKERARGS;  } WORKERARGS, *PWORKERARGS;
105    
106  // worker thread - main entry function  // worker thread - main entry function
107  DWORD WINAPI fractal_thread (LPVOID lpParam) {  DWORD WINAPI fractal_create_segment (LPVOID lpParam) {
108        
109    // thread stuff    // thread stuff
110    int thread_id;    int thread_id;
# Line 117  DWORD WINAPI fractal_thread (LPVOID lpPa Line 119  DWORD WINAPI fractal_thread (LPVOID lpPa
119        
120    // get worker arguments    // get worker arguments
121    args = (PWORKERARGS)lpParam;    args = (PWORKERARGS)lpParam;
     
   printf("----------------------------------------------\n");  
   printf("thread_id: %i\n", thread_id);  
   printf("arg.start_row: %i\n", args->start_row);  
   printf("arg.number_of_rows: %i\n", args->number_of_rows);  
122    
123    // calculate pointer to beginning of segment    // calculate pointer to beginning of segment
124    pDataBitmapSegment = (unsigned char *)((INT_PTR)args->pBitmap + (YSIZE - (args->start_row + args->number_of_rows)) * 3 * XSIZE);    pDataBitmapSegment = (unsigned char *)((INT_PTR)args->pBitmap + (YSIZE - (args->start_row + args->number_of_rows)) * 3 * XSIZE);
125    printf("segment_start: %p\n", pDataBitmapSegment);  
126      // debugging
127      if (VERBOSE) {
128        fprintf(stdout, "----------------------------------------------\n");
129        fprintf(stdout, "thread_id: %i\n", thread_id);
130        fprintf(stdout, "arg.start_row: %i\n", args->start_row);
131        fprintf(stdout, "arg.number_of_rows: %i\n", args->number_of_rows);
132        fprintf(stdout, "segment_start: %p\n", pDataBitmapSegment);
133      }
134        
135    // calculate fractal    // calculate fractal
136    for (y = (args->start_row + args->number_of_rows) - 1; y >= args->start_row; y--) {    for (y = (args->start_row + args->number_of_rows) - 1; y >= args->start_row; y--) {
137      //printf("calc: thread=%i; y=%i            limits: %i,%i    p: %p\n", thread_id, y, args->start_row, args->number_of_rows, pDataBitmapSegment);      //fprintf(stdout, "calc: thread=%i; y=%i            limits: %i,%i    p: %p\n", thread_id, y, args->start_row, args->number_of_rows, pDataBitmapSegment);
138      for (x = 0; x < XSIZE; x++) {      for (x = 0; x < XSIZE; x++) {
139        getColorValuesAt(x * (2.0 / XSIZE) - 1.5, y * (2.0 / YSIZE) - 1.0, &bgr[2], &bgr[1], &bgr[0]);        getColorValuesAt(x * (2.0 / XSIZE) - 1.5, y * (2.0 / YSIZE) - 1.0, &bgr[2], &bgr[1], &bgr[0]);
140                
       // debugging  
       //printf("pointer: %p\n", pDataBitmapCurrent);  
         
141        // transfer color values to current pixel        // transfer color values to current pixel
142        pDataBitmapSegment[0] = bgr[0];        pDataBitmapSegment[0] = bgr[0];
143        pDataBitmapSegment[1] = bgr[1];        pDataBitmapSegment[1] = bgr[1];
# Line 145  DWORD WINAPI fractal_thread (LPVOID lpPa Line 147  DWORD WINAPI fractal_thread (LPVOID lpPa
147        pDataBitmapSegment += 3;        pDataBitmapSegment += 3;
148                
149      }      }
150      //no padding required because 1500%4 =0      //no padding required because 1500%4 =0 ???
151    }    }
152    
153    printf("thread finished: %i\n", thread_id);    if (VERBOSE)
154        fprintf(stdout, "thread finished: %i\n", thread_id);
155    return 0;    return 0;
156    
157  }  }
158    
159    BOOL scan_argv(int argc, char *argv[], char opt_name[], char *opt_value) {
160      int i;
161      char * opt_current_name;
162      char * opt_current_value;
163    
164      //printf("searching for: '%s'\n", opt_name);
165      
166      for (i = 1; i < argc; i++) {
167        opt_current_name = argv[i];
168        if (strcmp(opt_current_name, opt_name) == 0) {
169          opt_current_value = argv[i+1];
170          if (opt_current_value != NULL) {
171            strcpy(opt_value, opt_current_value);
172          }
173          return TRUE;
174        }
175      }
176      return FALSE;
177    }
178    
179    
180  int main(int argc, char *argv[]) {  int main(int argc, char *argv[]) {
181    
# Line 160  int main(int argc, char *argv[]) { Line 183  int main(int argc, char *argv[]) {
183    DWORD err;    DWORD err;
184    HANDLE hMap, hFile;    HANDLE hMap, hFile;
185    LPVOID pData;    LPVOID pData;
186    unsigned char *pDataBitmap, *pDataBitmapCurrent;    unsigned char *pDataBitmap;
187    
188    // workers    // workers
189    int workers = 5;    int workers;
190    int worker_index, worker_rows, worker_startrow;    int worker_index, worker_rows, worker_startrow;
191    HANDLE *worker_handles;    HANDLE *worker_handles;
   //struct WorkerArguments *worker_args;  
192    PWORKERARGS worker_args;    PWORKERARGS worker_args;
193      int worker_count;
194    
195      // threads or processes?
196      BOOL use_processes = FALSE;
197      BOOL is_worker_process = FALSE;
198      
199      // information for creating processes
200      STARTUPINFO si;
201      PROCESS_INFORMATION pi;
202      char szCmdline[65536];
203      
204      // command line stuff
205      char arg_option[1024];
206      char arg_value[1024];
207      char *bmp_filename;
208      char *verbose_option = "";
209        
   // create empty bmp-file (black background)  
   write_blank_file("test.bmp");  
210    
211    /* open file for reading and writing */    // parse command line arguments
212    hFile = CreateFile("test.bmp", GENERIC_WRITE|GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);    if (argc < 2) {
213    if (INVALID_HANDLE_VALUE == hFile) {      fprintf(stderr, "Can not run without arguments!\nPlease specify '-t {number of threads}' or '-p {number of processes}' and an image filename.\n");
214      err = GetLastError();      exit(EXIT_FAILURE);
215      printErrorAndExit("Error at CreateFile",err);    }
216      
217      if (scan_argv(argc, argv, "--verbose", arg_value)) {
218        VERBOSE = TRUE;
219      }
220      
221      if (scan_argv(argc, argv, "--worker", arg_value)) {
222        use_processes = TRUE;
223        is_worker_process = TRUE;
224      
225      } else if (scan_argv(argc, argv, "-p", arg_value)) {
226        if (strlen(arg_value) == 0) {
227          fprintf(stderr, "Please specify number of processes!\n");
228          exit(EXIT_FAILURE);
229        }
230        use_processes = TRUE;
231        is_worker_process = FALSE;
232        workers = atoi(arg_value);
233      
234      } else if (scan_argv(argc, argv, "-t", arg_value)) {
235        if (strlen(arg_value) == 0) {
236          fprintf(stderr, "Please specify number of threads!\n");
237          exit(EXIT_FAILURE);
238        }
239        use_processes = FALSE;
240        is_worker_process = FALSE;
241        workers = atoi(arg_value);
242        
243    }    }
244      
245      
246      if (VERBOSE && use_processes) {
247        fprintf(stdout, "===================================================== ");
248        if (is_worker_process)
249          fprintf(stdout, "WORKER-PROCESS\n");
250        else
251          fprintf(stdout, "MASTER-PROCESS\n");
252      }
253    
254      
255      // master creates memory mapped file ("empty" image)
256      if (!is_worker_process) {
257        
258        if (argc < 4) {
259          fprintf(stderr, "Must give filename of image as third argument!\n");
260          exit(EXIT_FAILURE);
261        }
262        
263        bmp_filename = argv[3];
264        
265        // create empty bmp-file (black background)
266        write_blank_file(bmp_filename);
267    
268        // open file for reading and writing
269        hFile = CreateFile(bmp_filename, GENERIC_WRITE|GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
270        if (INVALID_HANDLE_VALUE == hFile) {
271          err = GetLastError();
272          printErrorAndExit("Error at CreateFile",err);
273        }
274    
275    /* create the file mapping object */      // create the file mapping object
276    hMap = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 0, NULL);      hMap = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 0, "bmp_fractal");
277    if (NULL == hMap) {      if (NULL == hMap) {
278      printErrorAndExit("Error at CreateFileMapping", GetLastError());        printErrorAndExit("Error at CreateFileMapping", GetLastError());
279        }
280      
281      // worker uses existing memory mapped file
282      } else {
283        
284        // open existing mapping object
285        hMap = OpenFileMapping(FILE_MAP_WRITE, FALSE, "bmp_fractal");
286        if (NULL == hMap)
287          printErrorAndExit("Error at OpenFileMapping", GetLastError());
288    }    }
289        
290    /* map the whole file into the process context */    // map the whole file into the process context
291    pData = MapViewOfFile(hMap, FILE_MAP_WRITE, 0, 0, 0);    pData = MapViewOfFile(hMap, FILE_MAP_WRITE, 0, 0, 0);
292    if (NULL == pData) {    if (NULL == pData) {
293      printErrorAndExit("Error at MapViewOfFile", GetLastError());      printErrorAndExit("Error at MapViewOfFile", GetLastError());
# Line 197  int main(int argc, char *argv[]) { Line 298  int main(int argc, char *argv[]) {
298    pDataBitmap = (unsigned char *)((INT_PTR)pData + sizeof(header));    pDataBitmap = (unsigned char *)((INT_PTR)pData + sizeof(header));
299        
300    // debugging    // debugging
301    printf("pos. of file: %p\n", pData);    if (VERBOSE) {
302    printf("pos. of bitmap: %p\n", pDataBitmap);      fprintf(stdout, "pos. of file: %p\n", pData);
303        fprintf(stdout, "pos. of bitmap: %p\n", pDataBitmap);
304    // pointer to current pixel    }
   pDataBitmapCurrent = pDataBitmap;  
305    
306      
307      if (use_processes && is_worker_process) {
308      
309        if (VERBOSE)
310          fprintf(stdout, "inside worker-process\n");
311        
312        // get segment information from command line
313        worker_startrow = atoi(argv[2]);
314        worker_rows = atoi(argv[3]);
315        
316        // allocate memory for one worker's arguments
317        if ((worker_args = malloc(sizeof(worker_args[0]))) == NULL)
318          perror("Error while allocating memory for worker arguments via malloc"), exit(1);
319        
320        // assign worker's arguments
321        worker_args[0].start_row = worker_startrow;
322        worker_args[0].number_of_rows = worker_rows;
323        worker_args[0].pBitmap = pDataBitmap;
324    
325        fractal_create_segment(&worker_args[0]);
326    
327        // cleanup mmap-handle
328        if (!CloseHandle(hMap))
329          printErrorAndExit("Error at CloseHandle", GetLastError());
330        
331        return 0;
332      }
333      
334    /*    /*
335    // turn bitmap into white wand    // turn bitmap into white canvas
336    for (offset = 0; offset < 500 * 500 * 3; offset++) {    for (offset = 0; offset < 500 * 500 * 3; offset++) {
337      //pDataBitmap[offset] = 255;      *pDataBitmap = 255;
338      *pDataBitmapCurrent = 255;      pDataBitmap++;
     pDataBitmapCurrent++;  
339    }    }
340      exit(0);
341    */    */
342    
343      // allocate memory for bitmap
344    // allocate memory for table of all worker handles    /*
345    if ((worker_handles = malloc(workers * sizeof worker_handles[0])) == NULL)    if ((pDataBitmap = malloc(XSIZE * YSIZE * 3 * sizeof(pDataBitmap[0]))) == NULL)
346      perror("malloc"), exit(1);      perror("malloc"), exit(1);
347      */
348      
349      // allocate memory for table of all worker handles
350      if ((worker_handles = malloc(workers * sizeof(worker_handles[0]))) == NULL)
351        perror("Error while allocating memory for worker handles via malloc"), exit(1);
352    
353    // allocate memory for table of all worker arguments    // allocate memory for table of all worker arguments
354    if ((worker_args = malloc(workers * sizeof worker_args[0])) == NULL)    if ((worker_args = malloc(workers * sizeof(worker_args[0]))) == NULL)
355      perror("malloc"), exit(1);      perror("Error while allocating memory for worker arguments via malloc"), exit(1);
356        
   // allocate memory for table of all worker arguments  
   /*  
   worker_args = (PWORKERARGS) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY | HEAP_NO_SERIALIZE, workers * sizeof(WORKERARGS));  
   
   if (worker_args == NULL) {  
     printErrorAndExit("Failed to allocate on heap", GetLastError());  
   }  
   */  
357        
358    // calculate segments of bitmap for worker threads/processes and start them    // calculate bitmap segment length for workers
359    worker_rows = YSIZE / workers;    worker_rows = YSIZE / workers;
360    printf("rows for each worker: %i\n", worker_rows);    if (VERBOSE)
361        fprintf(stdout, "rows for each worker: %i\n", worker_rows);
362      
363      // start workers
364    for (worker_index = 0; worker_index < workers; worker_index++) {    for (worker_index = 0; worker_index < workers; worker_index++) {
365            
366      // debugging: just run with single thread      // debugging: just run single thread
367      //if (worker_index == 1)      //if (worker_index == 1)
368      //  continue;      //  continue;
369            
# Line 245  int main(int argc, char *argv[]) { Line 373  int main(int argc, char *argv[]) {
373      // recalculate number of rows for last worker if (YSIZE mod workers) != 0      // recalculate number of rows for last worker if (YSIZE mod workers) != 0
374      if (worker_index == workers - 1) {      if (worker_index == workers - 1) {
375        worker_rows = YSIZE - worker_startrow;        worker_rows = YSIZE - worker_startrow;
376        printf("rows for last worker: %i\n", worker_rows);        if (VERBOSE)
377            fprintf(stdout, "rows for last worker: %i\n", worker_rows);
378      }      }
379            
380        // assign each worker's arguments
381      worker_args[worker_index].start_row = worker_startrow;      worker_args[worker_index].start_row = worker_startrow;
382      worker_args[worker_index].number_of_rows = worker_rows;      worker_args[worker_index].number_of_rows = worker_rows;
383      worker_args[worker_index].pBitmap = pDataBitmap;      worker_args[worker_index].pBitmap = pDataBitmap;
384            
385      worker_handles[worker_index] = CreateThread(      if (!use_processes) {
386        NULL,                          // LPSECURITY_ATTRIBUTES lpThreadAttributes,      
387        0,                             // SIZE_T dwStackSize,        worker_handles[worker_index] = CreateThread(
388        fractal_thread,                // LPTHREAD_START_ROUTINE lpStartAddress,          NULL,                          // LPSECURITY_ATTRIBUTES lpThreadAttributes,
389        &worker_args[worker_index],    // LPVOID lpParameter,          0,                             // SIZE_T dwStackSize,
390        0,                             // DWORD dwCreationFlags,          &fractal_create_segment,                // LPTHREAD_START_ROUTINE lpStartAddress,
391        NULL                           // LPDWORD lpThreadId          &worker_args[worker_index],    // LPVOID lpParameter,
392      );          0,                             // DWORD dwCreationFlags,
393            NULL                           // LPDWORD lpThreadId
394          );
395    
396          if (!worker_handles[worker_index])
397            printErrorAndExit("CreateThread failed", GetLastError());
398          
399        } else {
400    
401          if (VERBOSE)
402            verbose_option = "--verbose";
403          _snprintf(szCmdline, 1023, "%s %s %i %i %s", argv[0], "--worker", worker_startrow, worker_rows, verbose_option);
404          if (VERBOSE)
405            fprintf(stdout, "starting worker process: %s\n", szCmdline);
406          ZeroMemory( &si, sizeof(si) );
407          si.cb = sizeof(si);
408          ZeroMemory( &pi, sizeof(pi) );
409          
410          if (!CreateProcess(
411              NULL,           // No module name (use command line)
412              szCmdline,      // Command line
413              NULL,           // Process handle not inheritable
414              NULL,           // Thread handle not inheritable
415              FALSE,          // Set handle inheritance to FALSE
416              0,              // No creation flags
417              NULL,           // Use parent's environment block
418              NULL,           // Use parent's starting directory
419              &si,            // Pointer to STARTUPINFO structure
420              &pi             // Pointer to PROCESS_INFORMATION structure
421          ))
422            printErrorAndExit("CreateProcess failed", GetLastError());
423            
424          worker_handles[worker_index] = pi.hProcess;
425          
426        }
427    
428    }    }
429    
430    // wait for all threads    if (VERBOSE)
431    if (WaitForMultipleObjects(workers, worker_handles, TRUE, INFINITE) == WAIT_FAILED)      fprintf(stdout, "waiting for workers to finish...\n");
432      perror("WaitForMultipleObjects");    
433      // wait for all workers
434      for (worker_index = 0; worker_index < workers; worker_index += MAXIMUM_WAIT_OBJECTS) {
435        worker_count = ((workers - worker_index) > MAXIMUM_WAIT_OBJECTS) ? MAXIMUM_WAIT_OBJECTS : (workers - worker_index);
436        if (WaitForMultipleObjects(worker_count, &worker_handles[worker_index], TRUE, INFINITE) == WAIT_FAILED)
437          printErrorAndExit("Error at WaitForMultipleObjects", GetLastError());
438      }
439    
440    // debugging: just run with single thread    // debugging: just run single thread
441    //if (WaitForSingleObject(worker_handles[0], INFINITE) == WAIT_FAILED)    //if (WaitForSingleObject(worker_handles[0], INFINITE) == WAIT_FAILED)
442    //  perror("WaitForSingleObject");    //  perror("WaitForSingleObject");
443    
# Line 275  int main(int argc, char *argv[]) { Line 445  int main(int argc, char *argv[]) {
445    for (worker_index = 0; worker_index < workers; worker_index++)    for (worker_index = 0; worker_index < workers; worker_index++)
446      CloseHandle(worker_handles[worker_index]);      CloseHandle(worker_handles[worker_index]);
447            
448    /* write the result into the file */    // write the result into the file
449    if (!FlushViewOfFile(pData, 0)) {    if (!FlushViewOfFile(pData, 0)) {
450      err = GetLastError();      err = GetLastError();
451      printErrorAndExit("Error at UnmapViewOfFile", err);      printErrorAndExit("Error at UnmapViewOfFile", err);
452    }    }
453    
454    /* remove the mapped file */    // remove the mapped file
455    if (!UnmapViewOfFile(pData)) {    if (!UnmapViewOfFile(pData)) {
456      err = GetLastError();      err = GetLastError();
457      printErrorAndExit("Error at UnmapViewOfFile", err);      printErrorAndExit("Error at UnmapViewOfFile", err);
458      exit(err);      exit(err);
459    }    }
460        
461    /* cleanup handles */    // cleanup handles
462    if (!CloseHandle(hMap) || !CloseHandle(hFile) ) {    if (!CloseHandle(hMap) || !CloseHandle(hFile) ) {
463      err = GetLastError();      err = GetLastError();
464      printErrorAndExit("Error at CloseHandle", err);      printErrorAndExit("Error at CloseHandle", err);
465    }    }
466    
467    /*    free(worker_args);
468    if (HeapFree(GetProcessHeap(), HEAP_ZERO_MEMORY | HEAP_NO_SERIALIZE, worker_args) != TRUE) {    free(worker_handles);
     printErrorAndExit("Call to HeapFree has failed", GetLastError());  
   }  
   */  
     
469        
470    return 0;    return 0;
471        

Legend:
Removed from v.1.8  
changed lines
  Added in v.1.16

MailToCvsAdmin">MailToCvsAdmin
ViewVC Help
Powered by ViewVC 1.1.26 RSS 2.0 feed