from barrier_wait) will modify the data of all threads, preparing them for the next iteration. The others go directly to the top of the loop and wait on the barrier at line 35.

¦ barrier_main.c

1 #include <pthread.h>

2 #include 'barrier.h'

3 #include 'errors.h'

4

5 #define THREADS 5

6 #define ARRAY 6

7 #define INLOOPS 1000

8 #define OUTLOOPS 10

9

10 /*

11 * Keep track of each thread.

12 */

13 typedef struct thread_tag {

14  pthread_t thread_id;

15  int number;

16  int increment;

17  int array[ARRAY];

18 } thread_t;

19

20 barrier_t barrier;

21 thread_t thread[THREADS];

22

23 /*

24 * Start routine for threads.

25 */

26 void *thread_routine (void *arg)

27 {

28 thread_t *self = (thread_t*)arg; /* Thread's thread_t */

29 int in_loop, out_loop, count, status;

30

31 /*

32 * Loop through OUTLOOPS barrier cycles.

33 */

34 for (out_loop = 0; out_loop < OUTLOOPS; out_loop++) {

35 status = barrier_wait (&barrier);

36 if (status > 0)

37 err_abort (status, 'Wait on barrier');

38

39 /*

40 * This inner loop just adds a value to each element in

41 * the working array.

42 */

43 for (in_loop = 0; in_loop < INLOOPS; in_loop++)

44  for (count = 0; count < ARRAY; count++)

45  self->array[count] += self->increment; 46

47 status = barrier_wait (&barrier);

48 if (status > 0)

49  err_abort (status, 'Wait on barrier');

50

51 /*

52 * The barrier causes one thread to return with the

53 * special return status -1. The thread receiving this

54 * value increments each element in the shared array.

55 */

56 if (status == -1) {

57  int thread_num;

58

59  for (thread_num = 0; thread_num < THREADS; thread_num++)

60  thread[thread_num].increment += 1;

61 }

62 }

63 return NULL;

64 }

65

66 int main (int arg, char *argv[])

67 {

68 int thread_count, array_count;

69 int status;

70

71 barrier_init (&barrier, THREADS);

72

73 /*

74 * Create a set of threads that will use the barrier.

75 */

76 for (thread_count = 0; thread_count < THREADS; thread_count++) { 7 7 thread [thread_count].increment = thread_count;

78 thread[thread_count].number = thread_count;

79

80 for (array_count = 0; array_count < ARRAY; array_count++)

81  thread[thread_count].array[array_count] = array_count + 1;

82

83 status = pthread_create (&thread[thread_count].thread_id,

84 NULL, thread_routine, (void*)&thread[thread_count]);

85 if (status != 0)

86  err_abort (status, 'Create thread');

87 }

88

89 /*

90 * Now join with each of the threads.

91 */

92 for (thread_count = 0; thread_count < THREADS; thread_count++) {

93 status = pthread_join (thread[thread_count].thread_id, NULL);

94 if (status != 0)

95  err_abort (status, 'Join thread');

96

97 printf ('%02d: (%d) ',

Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату