view TaskManager/kernel/ppe/Sem.cc @ 1874:039e6d5cf5b7 draft

improve spe tasklist pipeline IO thead priority
author Kohagura
date Mon, 30 Dec 2013 20:14:33 +0900
parents d4311f83377a
children f73ca57cdc81
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;
}