OS X在使用<semaphore.h>时报错

报错代码

warning: 'sem_init' is deprecated [-Wdeprecated-declarations]
		sem_init(&sem, 0, 1);

/usr/include/sys/semaphore.h:55:42: note: 'sem_init' has been explicitly marked deprecated here

int sem_init(sem_t *, int, unsigned int) __deprecated;

/usr/include/sys/cdefs.h:176:37: note: expanded from macro '__deprecated'
		#define __deprecated    __attribute__((deprecated))

warning: implicit declaration of function 'pthread_mutex_destory' is invalid in C99 [-Wimplicit-function-declaration]
		pthread_mutex_destory(&mutex);

warning: implicit declaration of function 'sem_destory' is invalid in C99 [-Wimplicit-function-declaration]
		sem_destory(&sem);

3 warnings generated.
Undefined symbols for architecture x86_64:
  "_pthread_mutex_destory", referenced from:
      _main in lab4-6244a3.o
  "_sem_destory", referenced from:
      _main in lab4-6244a3.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
./run: line 3: ./lab4: No such file or directory

原因

mac OS X 不支持sem_init()sem_destroy()

解决办法

  • sem_init(&sem, 0, 1)改成sem_open("sem", O_CREAT|O_EXCL, S_IRWXU, 0)
  • sem_destory(&sem)改成sem_unlink("sem");

另外,支持pthread_mutex_init(&mutex, NULL)却不支持pthread_mutex_destory(&mutex),所以我把它注释掉了。。。

原文地址:https://www.cnblogs.com/05410n/p/7822984.html