changeset 14:cc2e4f2c9ce8

some fix
author Masataka Kohagura <e085726@ie.u-ryukyu.ac.jp>
date Mon, 06 Jan 2014 14:36:04 +0900
parents 753289c70eb4
children 08beb7bff036
files parallel_processing/ppb_sem_counter/ppb_sem_counter.cc
diffstat 1 files changed, 18 insertions(+), 37 deletions(-) [+]
line wrap: on
line diff
--- a/parallel_processing/ppb_sem_counter/ppb_sem_counter.cc	Mon Jan 06 13:44:34 2014 +0900
+++ b/parallel_processing/ppb_sem_counter/ppb_sem_counter.cc	Mon Jan 06 14:36:04 2014 +0900
@@ -1,29 +1,24 @@
 #include <stdio.h>
 #include <pthread.h>
-
-#define THREAD_NUM 2
-#define DATA_NUM 10
+#include <unistd.h>
+#include <semaphore.h>
 
-typedef struct _thread_arg {
-    int thread_no;
-    int *data;
-    pthread_mutex_t *mutex;
-} thread_arg_t;
+#define MAX_THREAD_NUM 2
+#define THREAD_NUM 5
+
+sem_t sem;
 
 void *
 thread_func(void *arg)
 {
-    thread_arg_t *targ = (thread_arg_t *)arg;
-    int result;
+    long id = (long)arg;
 
-    /* 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);
-    }
+    /* starting semaphore and ending semaphore*/
+    sem_wait(&sem);
+    printf("Thread %ld started.\n", id);
+    sleep(1);
+    printf("Thread %ld finished.\n", id);
+    sem_post(&sem);
     return 0;
 }
 
@@ -31,33 +26,19 @@
 main()
 {
     pthread_t handle[THREAD_NUM];
-    thread_arg_t targ[THREAD_NUM];
-    int data[DATA_NUM];
-    int i;
-    pthread_mutex_t mutex;
+    long i;
 
     /* initialize */
-    for (i = 0; i < DATA_NUM; i++) data[i] = 0;
-
-    /* initialized mutex*/
-    pthread_mutex_init(&mutex, NULL);
+    sem_init(&sem, 0, MAX_THREAD_NUM);
 
     /* 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]);
-    }
+    for (i = 0; i < THREAD_NUM; ++i) pthread_create(&handle[i], NULL, &thread_func, (void*)i);
 
     /* wait for running all thread */
-    for (i = 0; i < THREAD_NUM; i++) pthread_join(handle[i], NULL);
+    for (i = 0; i < THREAD_NUM; ++i) pthread_join(handle[i], NULL);
 
     /* destroy mutex*/
-    pthread_mutex_destroy(&mutex);
+    sem_destroy(&sem);
 
-    for (i = 0; i < DATA_NUM; i++) printf("data%d : %d\n", i, data[i]);
     return 0;
 }