fork download
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <stdio.h>
  4. #include <pthread.h>
  5.  
  6. #define THREADS 5
  7. #define DATA 100
  8.  
  9. typedef struct _pthread_arg_t {
  10. pthread_t thread;
  11. int *data;
  12. unsigned int end;
  13. int max;
  14. } pthread_arg_t;
  15.  
  16. void* pthread_routine(void *arg) {
  17. pthread_arg_t *info = (pthread_arg_t*) arg;
  18. int *it = info->data,
  19. *end = info->data + info->end;
  20.  
  21. while (it < end) {
  22. if (*it > info->max) {
  23. info->max = *it;
  24. }
  25. it++;
  26. }
  27.  
  28. pthread_exit(NULL);
  29. }
  30.  
  31. int main(int argc, char *argv[]) {
  32. pthread_arg_t threads[THREADS];
  33. int data[DATA],
  34. thread = 0,
  35. limit = 0,
  36. result = 0;
  37.  
  38. memset(&threads, 0, sizeof(pthread_arg_t) * THREADS);
  39. memset(&data, 0, sizeof(int) * DATA);
  40.  
  41. while (limit < DATA) {
  42. /* you can replace this with randomm number */
  43. data[limit] = limit;
  44. limit++;
  45. }
  46.  
  47. limit = DATA/THREADS;
  48.  
  49. while (thread < THREADS) {
  50. threads[thread].data = &data[thread * limit];
  51. threads[thread].end = limit;
  52. if (pthread_create(&threads[thread].thread, NULL, pthread_routine, &threads[thread]) != 0) {
  53. /* do something */
  54. return 1;
  55. }
  56. thread++;
  57. }
  58.  
  59. thread = 0;
  60. while (thread < THREADS) {
  61. if (pthread_join(threads[thread].thread, NULL) != 0) {
  62. /* do something */
  63. return 1;
  64. }
  65. thread++;
  66. }
  67.  
  68. thread = 0;
  69. result = threads[0].max;
  70. printf("result:\n");
  71. while (thread < THREADS) {
  72. printf("\t%d - %d: %d\n",
  73. thread * limit,
  74. thread * limit + limit - 1,
  75. threads[thread].max);
  76. if (threads[thread].max > result) {
  77. result = threads[thread].max;
  78. }
  79. thread++;
  80. }
  81. printf("max\t%d\n", result);
  82.  
  83. return 0;
  84. }
Success #stdin #stdout 0s 44392KB
stdin
Standard input is empty
stdout
result:
	0 - 19: 19
	20 - 39: 39
	40 - 59: 59
	60 - 79: 79
	80 - 99: 99
max	99