Mercurial > hg > Game > Cerium
view TaskManager/kernel/ppe/Sem.cc @ 1187:d4311f83377a draft
Put in order Test directory
author | Daichi TOMA |
---|---|
date | Thu, 07 Jul 2011 13:31:02 +0900 |
parents | 4c209dd223cd |
children | 039e6d5cf5b7 |
line wrap: on
line source
#include "Sem.h" #include <pthread.h> Sem::Sem(int value) { sem = new sem_t; pthread_mutex_init(&sem->mutex, NULL); pthread_cond_init(&sem->cond, NULL); sem->value = value; } Sem::~Sem() { pthread_mutex_destroy(&sem->mutex); pthread_cond_destroy(&sem->cond); delete sem; } //P命令 //資源を確保する void Sem::sem_p() { pthread_mutex_lock(&sem->mutex); //セマフォ変数が0の時、他のスレッドが資源を解放するのを待つ while(sem->value == 0) { pthread_cond_wait(&sem->cond, &sem->mutex); } //atomic //sem->value--; //資源の確保 //count()のvalueを取得する際にアトミック操作が必要 __sync_fetch_and_sub(&sem->value,1); pthread_mutex_unlock(&sem->mutex); } //V命令 //資源を解放する void Sem::sem_v() { pthread_mutex_lock(&sem->mutex); //atomic //sem->value++; //資源の解放 __sync_fetch_and_add(&sem->value,1); //資源の解放を知らせる pthread_cond_signal(&sem->cond); pthread_mutex_unlock(&sem->mutex); } int Sem::count() { //semの値を返せばよい。 //atomic return sem->value; }