Tuesday, June 9, 2015

Semaphore in Linux

@Example
  -. source: semaphore.c
  -. build
    # gcc semaphore.c -lpthread

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
#include <fcntl.h>

#define SEMA_NAME "/Semaphore"
#define SEMA_CREATOPT O_CREAT
#define SEMA_MODE S_IRWXU
#define SEMA_INITVALUE 0

#define CS_SIZE 1024

void main_function(void);
void* thread_function(void* arg);

char criticalSection[CS_SIZE];


int main()
{
sem_t* sema;
pthread_t thread;
void* result;

sema = sem_open(SEMA_NAME, SEMA_CREATOPT, SEMA_MODE, SEMA_INITVALUE);
if (sema == SEM_FAILED)
{
perror("*** Semaphore Open Failure ***\n");
exit(EXIT_FAILURE);
}

if (pthread_create(&thread, NULL, thread_function, NULL))
{
perror("*** Thread Create Failure ***\n");
exit(EXIT_FAILURE);
}

// Main Loop
printf("Input some text. Enter 'end' to finish\n");
main_function();

pthread_join(thread, &result);
printf("*** Thread Joined ***\n");

sem_close(sema);
return 0;
}

void main_function(void)
{
sem_t* sema = sem_open(SEMA_NAME, 0, SEMA_MODE, 0);

while (strncmp("end", criticalSection, 3) != 0)
{
fgets(criticalSection, CS_SIZE, stdin);
sem_post(sema);
}
}

void* thread_function(void* arg)
{
sem_t* sema = sem_open(SEMA_NAME, 0, SEMA_MODE, 0);

sem_wait(sema);

while (strncmp("end", criticalSection, 3) != 0)
{
printf("[input] %s", criticalSection);
sem_wait(sema);
}

pthread_exit(NULL);
}

No comments:

Post a Comment