/* Thread routine for psum-array.c */void *sum_array(void *vargp) { long myid = *((long *)vargp); /* Extract thread ID */ long start = myid * nelems_per_thread; /* Start element index */ long end = start + nelems_per_thread; /* End element index */ long i; for (i = start; i < end; i++) { psum[myid] += i; } return NULL; }
为了充分利用寄存器,例程应使用局部变量:
C
1
2
3
4
5
6
7
8
9
10
/* Thread routine for psum-local.c */void *sum_local(void *vargp) { long myid = *((long *)vargp); /* Extract thread ID */ long start = myid * nelems_per_thread; /* Start element index */ long end = start + nelems_per_thread; /* End element index */ long i, sum = 0; for (i = start; i < end; i++) { sum += i; } psum[myid] = sum; return NULL; }