Mercurial > hg > Members > masakoha > testcode
changeset 11:f522b6bf6789
fix ppb_data_shared
author | Masataka Kohagura <e085726@ie.u-ryukyu.ac.jp> |
---|---|
date | Fri, 03 Jan 2014 21:09:01 +0900 |
parents | 51177cc6ab38 |
children | 47f90873a72c |
files | parallel_processing/ppb_data_shared/ppb_data_shared.cc |
diffstat | 1 files changed, 20 insertions(+), 7 deletions(-) [+] |
line wrap: on
line diff
--- a/parallel_processing/ppb_data_shared/ppb_data_shared.cc Fri Jan 03 02:03:11 2014 +0900 +++ b/parallel_processing/ppb_data_shared/ppb_data_shared.cc Fri Jan 03 21:09:01 2014 +0900 @@ -3,21 +3,26 @@ #define THREAD_NUM 2 #define DATA_NUM 10 -#define SPLIT_DATA_NUM (DATA_NUM / THREAD_NUM) typedef struct _thread_arg { int thread_no; int *data; + pthread_mutex_t *mutex; } thread_arg_t; void * thread_func(void *arg) { thread_arg_t *targ = (thread_arg_t *)arg; + int result; - for (int i = 0; i < SPLIT_DATA_NUM; i++) { - printf("thread%d : %d + 1 = %d\n", - targ->thread_no, targ->data[i], targ->data[i] + 1); + /* starting mutex and ending mutex*/ + for (int i = 0; i < DATA_NUM; i++) { + pthread_mutex_lock(targ->mutex); + result = targ->data[i] + 1; + sched_yield(); + targ->data[i] = result; + pthread_mutex_unlock(targ->mutex); } return 0; } @@ -29,21 +34,29 @@ thread_arg_t targ[THREAD_NUM]; int data[DATA_NUM]; int i; + pthread_mutex_t mutex; /* initialize */ - for (i = 0; i < DATA_NUM; i++) data[i] = i; + for (i = 0; i < DATA_NUM; i++) data[i] = 0; + + /* initialized mutex*/ + pthread_mutex_init(&mutex, NULL); /* spawn thread a number of THREAD_NUM */ for (i = 0; i < THREAD_NUM; i++) { targ[i].thread_no = i; + targ[i].data = data; + targ[i].mutex = &mutex; - /* divide a data into THREAD_NUM*/ - targ[i].data = &data[SPLIT_DATA_NUM * i]; /* spawn thread*/ pthread_create(&handle[i], NULL, &thread_func, (void*)&targ[i]); } /* wait for running all thread */ for (i = 0; i < THREAD_NUM; i++) pthread_join(handle[i], NULL); + + pthread_mutex_destroy(&mutex); + + for (i = 0; i < DATA_NUM; i++) printf("data%d : %d\n", i, data[i]); return 0; }