Application of semaphore and @synchronized of signal volume

Source: Internet
Author: User
Tags semaphore

1.//Create Global queue

dispatch_queue_t queue = dispatch_get_global_queue(0, 0);

Create semaphore

dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);

nsmutablearray *array = [nsmutablearray array];

for(int i = 0 ; i < 1000000; i + +) {

dispatch_async(queue, ^{

Dispatch_semaphore Semaphore is a multi-threaded synchronization mechanism based on counter. When multiple threads access a common resource, there is a problem of data error caused by the feature of multithreading, which causes it to wait for the previous thread to access the array

dispatch_semaphore_wait(semaphore, dispatch_time_forever);

[array addobject: [nsnumber numberwithint: i]];

});

}

2.

dispatch_queue_t queue = dispatch_get_global_queue(0, 0);

nsmutablearray *array = [nsmutablearray array];

for(int i = 0 ; i < 1000000; i + +) {

dispatch_async(queue, ^{

Adds a lock to the array object. Prevents thread access at the same time.

@synchronized (array) {

[Array addobject: [nsnumber numberwithint: i]];

NSLog(@ "%d%@", I,array);

            }      

});

}

Application of semaphore and @synchronized of signal volume

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.