osx下信号量和锁无法使用的替代品

osx下进行同步的时候,无论是使用pthread_mutex_t还是sem_t 都无法满足要求,pthread_mutex_t根本就没用,sem_t 只能使用sem_open进行非匿名信号量初始化,但也无法解决同步问题,还是会造成错误,在stackoverflow上看到一个好方法,可以解决这个问题,
使用dispatch_semaphore_t。具体测试代码如下

/** main.c **/
#include <stdio.h>
#include <pthread.h>
#include <dispatch/dispatch.h>

int _times=1000000;
int a=0;
dispatch_semaphore_t semaphore;


void xx(const char *x){
printf("%s %d\n",x,a);
}

void f(){
  for(int i=0;i<_times;++i){
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
++a;
dispatch_semaphore_signal(semaphore);
  }
  xx("f");
  return;
}

int main(int argc, const char * argv[]) {
  pthread_t p;
  semaphore = dispatch_semaphore_create(1);
  pthread_create(&p,0, f,0);
  for(int i=0;i<_times;++i){
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    ++a;
    dispatch_semaphore_signal(semaphore);
  }
  xx("main");
  pthread_join(p,0);
  dispatch_release(semaphore);
  return 0;
}

使用sem_t的时候,最后输出结果不是200000,但是使用上面的代码,输出是200000

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值