2009/05/19

semaphore

A simple semaphore program modified from Beginning Linux Programming 4/e. The sem_getvalue() is used to get semaphore value for test purpose only.And also the return value of a thread is given by pthread_exit() in thread function.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>

#define  SIZE   64
char     work_area[SIZE];
sem_t    b_semaphore; // binary semaphore

void *thread_func(void *arg)
{
int sval;

sem_getvalue(&b_semaphore, &sval);
printf("Semaphore Value at thread_func() begining = %d\n", sval);

sem_wait(&b_semaphore);
sem_getvalue(&b_semaphore, &sval);
printf("Semaphore Value after first sem_wait() = %d\n", sval);

while(strncmp("end", work_area, 3)!=0) {
     printf("[%2d] - %s\n", strlen(work_area)-1, work_area);
     sem_wait(&b_semaphore);
     sem_getvalue(&b_semaphore, &sval);
     printf("Semaphore Value in thread_func() = %d\n", sval);
}

pthread_exit("WoW ! End of Thread...\n");
}

int main()
{
int sval;

pthread_t thread_1;
void *thread_result;

sem_init(&b_semaphore, 0, 0);
sem_getvalue(&b_semaphore, &sval);
printf("Semaphore Value after sem_init() = %d\n", sval);

pthread_create(&thread_1, NULL, thread_func, NULL);

printf("Input something, and 'end' to exit\n");
while( strncmp("end", work_area, 3)!=0) {
    printf("Input : ");
    fgets(work_area, SIZE, stdin);

    sem_post(&b_semaphore);

    sem_getvalue(&b_semaphore, &sval);
    printf("Semaphore Value after sem_post() = %d\n", sval);
    sleep(1);
}

printf("Waiting for thread to finish program...\n");
pthread_join(thread_1, &thread_result);

printf("Thread Result : %s\n", (char *)thread_result);
sem_destroy(&b_semaphore);

return 0;
}
$ gcc semaphore.c -o semaphore -lpthread $ ./semaphore
Semaphore Value after sem_init() = 0
Semaphore Value at thread_func() begining = 0
Input something, and 'end' to exit
Input : 1234
Semaphore Value after first sem_wait() = 0
[ 4] - 1234

Semaphore Value after sem_post() = 0
Input : Hello Semaphore !
Semaphore Value after sem_post() = 1
Semaphore Value in thread_func() = 0
[17] - Hello Semaphore !

Input : end
Semaphore Value after sem_post() = 1
Semaphore Value in thread_func() = 0
Waiting for thread to finish program...
Thread Result : WoW ! End of Thread...
From above results, we know the semaphore is immediately taken away by thread when it is just released by main thread. But after that, it is not. Why ? Need to test more :) .

沒有留言: