并发多线程,多个资源的情况下,使用信号量。
并发多线程,单个资源的情况下,使用mutex。
6辆车,3个停车位的问题:
-(void)testsemph{ dispatch_semaphore_t semaphores = dispatch_semaphore_create(3); for(int i =0;i<6; i++) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{ dispatch_semaphore_wait( semaphores, DISPATCH_TIME_FOREVER); NSLog(@" car %d input the plsition",i); sleep(2); dispatch_semaphore_signal(semaphores); NSLog(@" car %d leave the plsition",i); }); } }
2020-12-16 16:17:43.889732+0800 sempher[76427:2940388] car 0 input the plsition 2020-12-16 16:17:43.889811+0800 sempher[76427:2940389] car 1 input the plsition 2020-12-16 16:17:43.890044+0800 sempher[76427:2940390] car 2 input the plsition 2020-12-16 16:17:45.894960+0800 sempher[76427:2940389] car 1 leave the plsition 2020-12-16 16:17:45.895105+0800 sempher[76427:2940390] car 2 leave the plsition 2020-12-16 16:17:45.895478+0800 sempher[76427:2940391] car 4 input the plsition 2020-12-16 16:17:45.895506+0800 sempher[76427:2940387] car 3 input the plsition 2020-12-16 16:17:45.894954+0800 sempher[76427:2940388] car 0 leave the plsition 2020-12-16 16:17:45.895907+0800 sempher[76427:2940399] car 5 input the plsition 2020-12-16 16:17:47.900862+0800 sempher[76427:2940391] car 4 leave the plsition 2020-12-16 16:17:47.900900+0800 sempher[76427:2940399] car 5 leave the plsition 2020-12-16 16:17:47.901183+0800 sempher[76427:2940387] car 3 leave the plsition