iOS下用sem_init初始化信号量总是返回-1

时间:2021-11-11 15:18:34

总是返回-1说明初始化错误,原因是由于iOS不支持创建无名的信号量所至。

解决方案是造建有名的信号量。

代码如下:

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <assert.h>
#include <semaphore.h>

sem_t * CreateSemaphore( const char * inName, const int inStartingCount );
bool DestroySemaphore( sem_t * inSemaphore );
void SignalSemaphore( sem_t * inSemaphore );
void WaitSemaphore( sem_t * inSemaphore );
bool TryWaitSemaphore( sem_t * inSemaphore );
bool ClearSemaphore( const char * inName);

//
sem_t * CreateSemaphore( const char * inName, const int inStartingCount )
{
	sem_t * semaphore = sem_open( inName, O_CREAT, 0644, inStartingCount );
    
	//
	if( semaphore == SEM_FAILED )
	{
		switch( errno )
		{
            case EEXIST:
                printf( "Semaphore with name '%s' already exists.\n", inName );
                break;
                
            default:
                printf( "Unhandled error: %d.\n", errno );
                break;
		}
        
		//
		assert(false);
		return SEM_FAILED;
	}
    
	//
	return semaphore;
}


//
bool DestroySemaphore( sem_t * inSemaphore )
{
	int retErr = sem_close( inSemaphore );
    
	//
	if( retErr == -1 )
	{
		//
		switch( errno )
		{
            case EINVAL:
                printf( "inSemaphore is not a valid sem_t object." );
                break;
                
            default:
                printf( "Unhandled error: %d.\n", errno );
                break;
		}
        
		//
		assert(false);
		return false;
	}
    
	//
	return true;
}

//
void SignalSemaphore( sem_t * inSemaphore )
{
	sem_post( inSemaphore );
}

//
void WaitSemaphore( sem_t * inSemaphore )
{
	sem_wait( inSemaphore );
}

//
bool TryWaitSemaphore( sem_t * inSemaphore )
{
	int retErr = sem_trywait( inSemaphore );
    
	//
	if( retErr == -1 )
	{
		//
		if( errno != EAGAIN )
		{
			printf( "Unhandled error: %d\n", errno );
			assert( false );
		}
        
		//
		return false;
	}
    
	//
	return true;
}

bool ClearSemaphore( const char * inName)
{
    int retErr = sem_unlink(inName);
    
    if (retErr == -1) {
        
        return false;
        
    }
    
    return true;
}


使用完后还要记得

//使用sem_open方式创建的信号量在使用完毕需清除.
ClearSemaphore("mysem");




Reference:

http://getoffmylawnentertainment.com/blog/2011/06/27/sem_init-function-not-implemented/

http://www.lastrayofhope.com/2011/03/15/ios-semaphore-problems/