Mercurial > hg > Game > Cerium
view TaskManager/kernel/ppe/Sem.cc @ 2069:26aa08c9a1de draft default tip
cuda example fix
author | Shinji KONO <kono@ie.u-ryukyu.ac.jp> |
---|---|
date | Sun, 12 Feb 2017 10:04:55 +0900 |
parents | f73ca57cdc81 |
children |
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); } void Sem::sem_v1() { pthread_mutex_lock(&sem->mutex); //atomic sem->value = 1; //__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; }