Mercurial > hg > Applications > Grep
view parallel_processing/ppb_sem_counter/ppb_sem_counter.cc @ 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 |
line wrap: on
line source
#include <stdio.h> #include <pthread.h> #include <unistd.h> #include <semaphore.h> #define MAX_THREAD_NUM 2 #define THREAD_NUM 5 sem_t sem; void * thread_func(void *arg) { long id = (long)arg; /* 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; } int main() { pthread_t handle[THREAD_NUM]; long i; /* initialize */ sem_init(&sem, 0, MAX_THREAD_NUM); /* spawn thread a number of THREAD_NUM */ 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); /* destroy mutex*/ sem_destroy(&sem); return 0; }