# HG changeset patch # User Masataka Kohagura # Date 1388983474 -32400 # Node ID 753289c70eb4a8aa466234f23a831bce1a64b918 # Parent 47f90873a72c3a8bd4a319e00d7c95bc36fb1392 add ppb_sem_counter some files diff -r 47f90873a72c -r 753289c70eb4 parallel_processing/ppb_sem_counter/Makefile --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/parallel_processing/ppb_sem_counter/Makefile Mon Jan 06 13:44:34 2014 +0900 @@ -0,0 +1,11 @@ +TARGET = ppb_sem_counter +CC = clang++ +CPPFLAGS = -g -O0 + +$(TARGET): $(TARGET).o + $(CC) -g -O0 -o $@ $< +$(TARGET).o: $(TARGET).cc + +clean: + rm -f $(TARGET) + rm -f *.o diff -r 47f90873a72c -r 753289c70eb4 parallel_processing/ppb_sem_counter/ppb_sem_counter.cc --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/parallel_processing/ppb_sem_counter/ppb_sem_counter.cc Mon Jan 06 13:44:34 2014 +0900 @@ -0,0 +1,63 @@ +#include +#include + +#define THREAD_NUM 2 +#define DATA_NUM 10 + +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; + + /* 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; +} + +int +main() +{ + pthread_t handle[THREAD_NUM]; + 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] = 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; + + /* 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); + + /* destroy mutex*/ + pthread_mutex_destroy(&mutex); + + for (i = 0; i < DATA_NUM; i++) printf("data%d : %d\n", i, data[i]); + return 0; +}