changeset 13:753289c70eb4

add ppb_sem_counter some files
author Masataka Kohagura <e085726@ie.u-ryukyu.ac.jp>
date Mon, 06 Jan 2014 13:44:34 +0900
parents 47f90873a72c
children cc2e4f2c9ce8
files parallel_processing/ppb_sem_counter/Makefile parallel_processing/ppb_sem_counter/ppb_sem_counter.cc
diffstat 2 files changed, 74 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /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
--- /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 <stdio.h>
+#include <pthread.h>
+
+#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;
+}