Multithreaded Programming Guide

Exit Print View

Updated: July 2014
 
 

Initialize a Semaphore

Use sema_init(3C) to initialize the semaphore variable pointed to by sp by count amount.

sema_init Syntax

#include <thread.h>

int sema_init(sema_t *sp, unsigned int count, int type,
    void *arg);

type can be one of the following values:

  • USYNC_PROCESS. The semaphore can be used to synchronize threads in this process and other processes. Only one process should initialize the semaphore. arg is ignored.

  • USYNC_THREAD. The semaphore can be used to synchronize threads in this process, only. arg is ignored.

Multiple threads must not initialize the same semaphore simultaneously. A semaphore must not be reinitialized while other threads might be using the semaphore.

Semaphores With Intraprocess Scope
#include <thread.h>

sema_t sp;
int ret;
int count;
count = 4;

/* to be used within this process only */
ret = sema_init(&sp, count, USYNC_THREAD, 0); 
Semaphores With Interprocess Scope
#include <thread.h>

sema_t sp;
int ret;
int count;
count = 4;

/* to be used among all the processes */
ret = sema_init (&sp, count, USYNC_PROCESS, 0); 

sema_init Return Values

sema_init() returns 0 if successful. When any of the following conditions is detected, sema_init() fails and returns the corresponding value.

EINVAL

Description: sp refers to an invalid semaphore.

EFAULT

Description: Either sp or arg point to an illegal address.