from 스터디룸 2008.04.23 10:26

Semaphore

/***************************************
 * Title: Semaphore
 * Desc: counting Semaphore
 ***************************************/
#include <stdio.h>
#include <semaphore.h>
#include <pthread.h>

/*TODO: semaphore variable - sem */
sem_t sema;
 
pthread_t   task;

void Thread( void ) {
    int i = 0;
    int val;
 
    while(1) {
        i++;
        /* TODO: acquire a semaphore */
        sem_wait(&sema);
       
        /* TODO: get the value of a semaphore */
        sem_getvalue(&sema, &val);
       
        printf( "wakeup %d: value = %d\n", i ,val );
       
        if ( i > 5 ) break;
    }
}

int main( void )
{
    int i = 0, j, val;
    /* TODO: initialize unnamed semaphore, value is 3 , in case of binary:1*/
    sem_init (&sema, 0, 3);
   
    pthread_create( &task, NULL, (void*(*)(void*))Thread, NULL );
   
    while(1) {
        i++;
        printf( "sem post %d\n", i );
        /* TODO: release semaphore */
        sem_post(&sema);
       
        /* TODO: get the value of a semaphore */
        sem_getvalue(&sema, &val);
       
       
       
        printf( "sem value = %d\n", val );
        if ( i > 5 ) break;
       
        for( j = 0; j<5000000; j++ );
    }
}


MUTEX (Mutual Exclusion Semaphore)

/***************************************
 * Title: Mutex
 * Desc: Mutex Semaphore for exclusion
 ***************************************/
#include <semaphore.h>
#include <pthread.h>

/* TODO: declare mutex object and initialize */
pthread_mutex_t mutex;
 
int val;
int arg1 = 0, arg2 = 1;
pthread_t  thread1, thread2, main_thread;
pthread_attr_t attr;

void *Thread( void* arg )
{
    int i, j;
   
    for( i = 0; ; i++ ) {
        /* TODO: lock mutex  */
        pthread_mutex_lock(&mutex);
       
        val = *(int*)arg;
        printk( "thread %d: %dth iteration: i = %d\n", *(int*)arg, i, val);
        for ( j=0; j<1000000; j++ );
        /* TODO: unlock mutex  */
         pthread_mutex_unlock(&mutex);
       
    }
}

int main( void * arg ) {

    int    error;
   
    struct sched_param param;
    int policy = SCHED_FIFO;
   
    /*TODO : set priority of main thread 150 */
    main_thread = pthread_self();
    param.sched_priority = 150;
    pthread_setschedparam(main_thread, policy, &param);
   
     
    /*TODO : initialize attr */
    pthread_attr_init(&attr);
   
    /*TODO : set scheduling policy of thread1 and thread2 to round-robin */

    //pthread_attr_setschedpolicy(&attr, SCHED_RR);
    attr.schedparam_policy = SCHED_RR;
   
    pthread_create( &thread1, &attr, (void*(*)(void*))Thread, &arg1 );
    pthread_create( &thread2, &attr, (void*(*)(void*))Thread, &arg2 );
   

    pthread_exit(0);

}


 

'스터디룸' 카테고리의 다른 글

Message Queue  (0) 2008.04.23
조건변수와 동기화  (0) 2008.04.23
Semaphore와 Mutex  (0) 2008.04.23
쓰레드 스케줄링 구현  (2) 2008.04.22
UML 사용자 지침서  (0) 2008.04.10