gcd-two network request synchronization issues

Source: Internet
Author: User

There are times when network requests are needed.

Two interface request data, then we can do the final data processing. But because the network request is the shift. We don't know when two requests are complete.

It's natural to think about this demand 多线程 . The moment to express the real technology comes, can use the group queue ah. The request tasks in the queue are complete and the main thread is notified to process the summarized data.

That's what I wrote today, but I found out that the main thread did not wait for the sub-thread network request in the queue Bock callback to return. I gave the block a callback before it was printed, and it was true that the queue's tasks were printed before the main thread returned. So where's the problem?

Network requests and processing of response data is a time-consuming operation and a common scenario in our development, and the process of performing other operations after the network request and processing of the response data is done is also a common scenario in our development. We can tell,

The task of the network request is to commit to the child thread asynchronous processing, the network request such a task is quickly completed, but the network request is a task, processing received network response is a task, take care not to confuse the two processes .

While receiving the network response and processing the data that returned the response is not performed in the child thread, we will find that the block of the callback response processing is executed in the main thread by printing the current thread in the block where the callback response is processed.

If you are familiar with block callback such a communication mechanism, it is not difficult to understand that this callback response block is actually called to execute the AFN framework is the underlying code, and this part of the code is clearly executed in the main thread.

At this point, if we need to make sure that the data received for the network response in the main thread is processed, the last action we need is final. In other words, since the thread will wait, receive a signal, only notify the main thread, their own real completion of the task.

This signal is the GCD signal. dispatch_semaphore_t
- (void) getnetworkingdata{NSString *appidkey =@ "8781E4EF1C73FF20A180D3D7A42A8C04";nsstring* urlstring_1 =@ "Http://api.openweathermap.org/data/2.5/weather";nsstring* urlstring_2 =@ "http://api.openweathermap.org/data/2.5/forecast/daily";nsdictionary* Dictionary [email protected]{@ "lat":@ "40.04991291",@ "Lon":@ "116.25626162",@ "APPID": Appidkey};Create groups dispatch_group_t group = Dispatch_group_create ();Add the first network request task to a group Dispatch_group_async (group, Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{Create semaphore dispatch_semaphore_t semaphore = dispatch_semaphore_create (0);Start Network request task Afhttpsessionmanager *manager = [Afhttpsessionmanager manager]; [Manager get:urlstring_1 Parameters:dictionary Progress:Nil success:^ (Nsurlsessiondatatask * _nonnull task,ID _nullable responseobject) {NSLog (@ "Successful request data 1:%@", [Responseobject class]);If the request succeeds, send the semaphore dispatch_semaphore_signal (semaphore); } failure:^ (Nsurlsessiondatatask * _nullable task,Nserror * _nonnull error) {NSLog (@ "Failed request data");If the request fails, the semaphore dispatch_semaphore_signal (semaphore) is also sent; }];Before the network request task succeeds, the semaphore waits for the dispatch_semaphore_wait (semaphore, dispatch_time_forever); });Add a second network request task to the group Dispatch_group_async (Group, Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{Create semaphore dispatch_semaphore_t semaphore = dispatch_semaphore_create (0);Start Network request task Afhttpsessionmanager *manager = [Afhttpsessionmanager manager]; [Manager get:urlstring_2 Parameters:dictionary Progress:Nil success:^ (Nsurlsessiondatatask * _nonnull task,id _nullable responseobject) {nslog (@ "Successful request data 2:%@", [Responseobject class]); //If the request is successful, send the semaphore dispatch_semaphore_signal (semaphore); } failure:^ (nsurlsessiondatatask * _nullable task, NSError * _nonnull error) {nslog (@ "failed request data"); //if the request fails, also sends the semaphore dispatch_semaphore_signal (semaphore);}]; //before network request task succeeds, Semaphore waits Dispatch_semaphore_wait (semaphore, dispatch_time_forever);}); Dispatch_group_notify (Group, Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{nslog (@ "completed the network request, Whether the network request has failed or succeeded. "); }); }

The concrete steps to do this are this. In the self-thread queue. Set the signal to wait until the block callback is complete (in the main thread) to send the signal. The child thread receives a signal before it notifies dispatch_group_notify the child that the request data is actually returned.

When using it, make sure you know which one to wait for and which thread to send.



Wen/Suyongmao (Jane book author)
Original link: http://www.jianshu.com/p/943dcb9ad632
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

gcd-two network request synchronization issues

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.