Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- //put numbers 0 to N into an array
- //sum numers from 2 arrs into 3rd
- #define N 12//note this is 12 and not 10
- long thread_elems = N/4;
- /* A structure we'll use to pass arguments to our thread function. */
- struct thread_arg {
- //sum numbers from 2 arrs into 3rd
- long arr1[N];
- long arr2[N];
- long arr3[N];
- int id;
- };
- void *sum(void *varg){
- struct thread_arg chunk= *((struct thread_arg*)varg);
- long start = (chunk.id)*thread_elems;
- long end = start + thread_elems;
- long i,sum=0;
- for (i=start; i<end;i++){
- //store the int to our retArr
- //if end < N{
- printf("%d %d ", chunk.arr1[i], chunk.arr2[i]);
- chunk.arr3[i] = chunk.arr1[i] + chunk.arr2[i];
- (*((struct thread_arg*)varg)).arr3[i] = (*((struct thread_arg*)varg)).arr1[i] + (*((struct thread_arg*)varg)).arr2[i];
- printf(" %d ", chunk.arr3[i]);
- //}
- }
- printf("\n");
- }
- int main(){
- pthread_t tid[4];
- // ids[4];
- long ret_arr[N];
- struct thread_arg *arguments = malloc(4 * sizeof(struct thread_arg));
- //build arrs in struct from arrays in HOST memory
- int i, j;
- for (i=0; i<4; i++){
- for(j=0;j<N;j++){
- (arguments[i]).arr1[j]= j;
- (arguments[i]).arr2[j]= j;
- printf("%d %d ", (arguments[i]).arr1[j], (arguments[i]).arr2[j]);
- }
- }
- printf("\n");
- for (i=0; i<4; i++){
- (arguments[i]).id = i;
- pthread_create(&tid[i], NULL, sum, (void*)&arguments[i]);
- }
- //don't destroy threads until they are all done!
- for (i=0;i<4;i++){
- pthread_join(tid[i], NULL);
- }
- for(j=0;j<N;j++){
- printf(" %d ", (arguments[0]).arr3[j] );
- }
- //get the results into a single arr
- //arg arrays are disjoint and don't share mem!
- long t, start, end;
- for (i=0;i<4;i++){
- start = i*thread_elems;
- end = start + thread_elems;
- for(t=start; t<end; t++){
- ret_arr[t] = (arguments[i]).arr3[t];
- }
- }
- for (i=0;i<N;i++){
- printf("%d ", ret_arr[i]);
- }
- printf("\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement