GVKun编程网logo

iOS 之多线程 NSThread(ios多线程nsoperation)

4

如果您想了解iOS之多线程NSThread和ios多线程nsoperation的知识,那么本篇文章将是您的不二之选。我们将深入剖析iOS之多线程NSThread的各个方面,并为您解答ios多线程nso

如果您想了解iOS 之多线程 NSThreadios多线程nsoperation的知识,那么本篇文章将是您的不二之选。我们将深入剖析iOS 之多线程 NSThread的各个方面,并为您解答ios多线程nsoperation的疑在这篇文章中,我们将为您介绍iOS 之多线程 NSThread的相关知识,同时也会详细的解释ios多线程nsoperation的运用方法,并给出实际的案例分析,希望能帮助到您!

本文目录一览:

iOS 之多线程 NSThread(ios多线程nsoperation)

iOS 之多线程 NSThread(ios多线程nsoperation)

trackback:http://www.cnblogs.com/ligun123/archive/2011/09/10/2173121.html


iOS 支持多个层次的多线程编程,层次越高的抽象程度越高,使用起来也越方便,也是苹果最推荐使用的方法。下面根据抽象层次从低到高依次列出iOS所支持的多线程编程范式:
1,Thread;
2,Cocoa operations;
3,Grand Central dispatch (GCD) (iOS4 才开始支持)

下面简要说明这三种不同范式:
Thread 是这三种范式里面相对轻量级的,但也是使用起来最负责的,你需要自己管理thread的生命周期,线程之间的同步。线程共享同一应用程序的部分内存空间,它们拥有对数据相同的访问权限。你得协调多个线程对同一数据的访问,一般做法是在访问之前加锁,这会导致一定的性能开销。在 iOS 中我们可以使用多种形式的 thread:
Cocoa threads: 使用NSThread 或直接从 NSObject 的类方法 performSelectorInBackground:withObject: 来创建一个线程。如果你选择thread来实现多线程,那么 NSThread 就是官方推荐优先选用的方式。
POSIX threads: 基于 C 语言的一个多线程库,

Cocoa operations是基于 Obective-C实现的,类 NSOperation 以面向对象的方式封装了用户需要执行的操作,我们只要聚焦于我们需要做的事情,而不必太操心线程的管理,同步等事情,因为NSOperation已经为我们封装了这些事情。 NSOperation 是一个抽象基类,我们必须使用它的子类。iOS 提供了两种默认实现:NSInvocationoperation 和 NSBlockOperation。

Grand Central dispatch (GCD): iOS4 才开始支持,它提供了一些新的特性,以及运行库来支持多核并行编程,它的关注点更高:如何在多个 cpu 上提升效率。

有了上面的总体框架,我们就能清楚地知道不同方式所处的层次以及可能的效率,便利性差异。下面我们先来看看 NSThread 的使用,包括创建,启动,同步,通信等相关知识。这些与 win32/Java 下的 thread 使用非常相似。

线程创建与启动
NSThread的创建主要有两种直接方式:
[NSThread detachNewThreadSelector:@selector(myThreadMainMethod:) toTarget:self withObject:nil];

NSThread* myThread = [[NSThread alloc] initWithTarget:self
                                        selector:@selector(myThreadMainMethod:)
                                        object:nil];
[myThread start];

这两种方式的区别是:前一种一调用就会立即创建一个线程来做事情;而后一种虽然你 alloc 了也 init了,但是要直到我们手动调用 start 启动线程时才会真正去创建线程。这种延迟实现思想在很多跟资源相关的地方都有用到。后一种方式我们还可以在启动线程之前,对线程进行配置,比如设置 stack 大小,线程优先级。

还有一种间接的方式,更加方便,我们甚至不需要显式编写 NSThread 相关代码。那就是利用 NSObject 的类方法 performSelectorInBackground:withObject: 来创建一个线程:

[myObj performSelectorInBackground:@selector(myThreadMainMethod) withObject:nil];

其效果与 NSThread 的 detachNewThreadSelector:toTarget:withObject: 是一样的。


线程同步
线程的同步方法跟其他系统下类似,我们可以用原子操作,可以用 mutex,lock等。
iOS的原子操作函数是以 OSAtomic开头的,比如:OSAtomicAdd32,OSAtomicOr32等等。这些函数可以直接使用,因为它们是原子操作。

iOS中的 mutex 对应的是 NSLock,它遵循 NSLooking协议,我们可以使用 lock,tryLock,lockBeforeData:来加锁,用 unLock来解锁。使用示例:
BOOL moretoDo = YES;
NSLock *theLock = [[NSLock alloc] init];
...
while (moretoDo) {
    /* Do another increment of calculation */
    /* until there’s no more to do. */
    if ([theLock tryLock]) {
        /* Update display used by all threads. */
        [theLock unlock];
    }
}


我们可以使用指令 @synchronized 来简化 NSLock的使用,这样我们就不必显示编写创建NSLock,加锁并解锁相关代码。
- (void)myMethod:(id)anObj
{
    @synchronized(anObj)
    {
        // Everything between the braces is protected by the @synchronized directive.
    }
}


 
还有其他的一些锁对象,比如:循环锁NSRecursiveLock,条件锁NSConditionLock,分布式锁NSdistributedLock等等,在这里就不一一介绍了,大家去看官方文档吧。


用NSCodition同步执行的顺序
NSCodition 是一种特殊类型的锁,我们可以用它来同步操作执行的顺序。它与 mutex 的区别在于更加精准,等待某个 NSCondtion 的线程一直被 lock,直到其他线程给那个 condition 发送了信号。下面我们来看使用示例:

某个线程等待着事情去做,而有没有事情做是由其他线程通知它的。

[cocoaCondition lock];
while (timetoDoWork <= 0)
    [cocoaCondition wait];
 
timetoDoWork--; 
// Do real work here.
[cocoaCondition unlock];



其他线程发送信号通知上面的线程可以做事情了:
[cocoaCondition lock];
timetoDoWork++;
[cocoaCondition signal];
[cocoaCondition unlock];




线程间通信
线程在运行过程中,可能需要与其它线程进行通信。我们可以使用 NSObject 中的一些方法:
在应用程序主线程中做事情:
performSelectorOnMainThread:withObject:waitUntilDone:
performSelectorOnMainThread:withObject:waitUntilDone:modes:

在指定线程中做事情:
performSelector:onThread:withObject:waitUntilDone:
performSelector:onThread:withObject:waitUntilDone:modes:

在当前线程中做事情:
performSelector:withObject:afterDelay:
performSelector:withObject:afterDelay:inModes:

取消发送给当前线程的某个消息
cancelPrevIoUsPerformRequestsWithTarget:
cancelPrevIoUsPerformRequestsWithTarget:selector:object:

如在我们在某个线程中下载数据,下载完成之后要通知主线程中更新界面等等,可以使用如下接口:

- (void)myThreadMainMethod
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    // to do something in your thread job
    ...
    [self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:NO];
    [pool release];
}


RunLoop
说到 NSThread 就不能不说起与之关系相当紧密的 NSRunLoop。Run loop 相当于 win32 里面的消息循环机制,它可以让你根据事件/消息(鼠标消息,键盘消息,计时器消息等)来调度线程是忙碌还是闲置。
系统会自动为应用程序的主线程生成一个与之对应的 run loop 来处理其消息循环。在触摸 UIView 时之所以能够激发 touchesBegan/touchesMoved 等等函数被调用,就是因为应用程序的主线程在 UIApplicationMain 里面有这样一个 run loop 在分发 input 或 timer 事件。


参考资料:
NSRunLoop概述和原理:http://xubenyang.me/384

官方文档:http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Multithreading/

iOS multiple threads(1)-----NSThread

iOS multiple threads(1)-----NSThread

OSC 请你来轰趴啦!1028 苏州源创会,一起寻宝 AI 时代
   多线程编程在任何一门语言中都是重中之重,必须牢牢掌握住,就不废话啦。
   iOS 所支持的多线程编程范式有下面几种:
      1、 Thread;
      2、Cocoa operations;
      3、Grand Central Dispatch (GCD) (iOS4 才开始支持);
   而 iOS 支持多个层次的多线程编程,层次越高的抽象程度越高,使用起来也越方便,也是苹果最推荐使用的方法。上述的三种范式,抽象层次是从低到高,下面简要说明这三种不同范式特点吧:
     1、Thread 是这三种范式里面相对轻量级的,但也是使用起来最负责的,你需要自己管理 thread 的生命周期,线程之间的同步。线程共享同一应用程序的部分内存空间,它们拥有对数据相同的访问权限。你得协调多个线程对同一数据的访问,一般做法是在访问之前加锁,这会导致一定的性能开销。在 iOS 中我们可以使用多种形式的 thread:
     a、Cocoa threads: 使用 NSThread 或直接从 NSObject 的类方法 performSelectorInBackground:withObject: 来创建一个线程。如果你选择 thread 来实现多线程,那么 NSThread 就是官方推荐优先选用的方式。
     b、POSIX threads: 基于 C 语言的一个多线程库,
     2、Cocoa operations 是基于 Obective-C 实现的,类 NSOperation 以面向对象的方式封装了用户需要执行的操作,我们只要聚焦于我们需要做的事情,而不必太操心线程的管理,同步等事情,因为 NSOperation 已经为我们封装了这些事情。 NSOperation 是一个抽象基类,我们必须使用它的子类。iOS 提供了两种默认实现:NSInvocationOperation 和 NSBlockOperation。
     3、Grand Central Dispatch (GCD): iOS4 才开始支持,它提供了一些新的特性,以及运行库来支持多核并行编程,它的关注点更高:如何在多个 cpu 上提升效率。
   下面,我们来依次举例细说上述几种方式创建多线程的方式和特点。
   首先,我们来看看 NSThread 的使用,包括创建,启动,同步,通信等相关知识。这些与 win32/Java 下的 thread 使用非常相似

   线程创建与启动 

   NSThread 的创建主要有两种直接方式:

   1、 [NSThread detachNewThreadSelector:@selector(myThreadMainMethod:) toTarget:self withObject:nil];
   2、 NSThread* myThread = [[NSThread alloc] initWithTarget:self
                                        selector:@selector(myThreadMainMethod: )
                                        object:nil];
      [myThread start];


    这两种方式的区别是:前一种一调用就会立即创建一个线程来做事情;而后一种虽然你 alloc 了也 init 了,但是要直到我们手动调用 start 启动线程时才会真正去创建线程。这种延迟实现思想在很多跟资源相关的地方都有用到。后一种方式我们还可以在启动线程之前,对线程进行配置,比如设置 stack 大小,线程优先级。
  还有一种间接的方式,更加方便,我们甚至不需要显式编写 NSThread 相关代码。那就是利用 NSObject 的类方法
   performSelectorInBackground:withObject: 来创建一个线程:
   [myObj performSelectorInBackground:@selector(myThreadMainMethod) withObject:nil];
   其效果与 NSThread 的 detachNewThreadSelector:toTarget:withObject: 是一样的。
   线程同步
   线程的同步方法跟其他系统下类似,我们可以用原子操作,可以用 mutex,lock 等。
   iOS 的原子操作函数是以 OSAtomic 开头的,比如:OSAtomicAdd32, OSAtomicOr32 等等。这些函数可以直接使用,因为它们是原子操作。
   iOS 中的 mutex 对应的是 NSLock,它遵循 NSLooking 协议,我们可以使用 lock, tryLock, lockBeforeData: 来加锁,用 unLock 来解锁。使用示例:
BOOL moreToDo = YES;
NSLock *theLock = [[NSLock alloc] init];
...
while (moreToDo) {
    /* Do another increment of calculation */
    /* until there’s no more to do. */
    if ([theLock tryLock]) {
        /* Update display used by all threads. */
        [theLock unlock];
    }
}

   我们可以使用指令 @synchronized 来简化 NSLock 的使用,这样我们就不必显示编写创建 NSLock, 加锁并解锁相关代码。
- (void)myMethod:(id)anObj
{
    @synchronized(anObj)
    {
        // Everything between the braces is protected by the @synchronized directive.
    }
}

   还有其他的一些锁对象,比如:循环锁 NSRecursiveLock,条件锁 NSConditionLock,分布式锁 NSDistributedLock 等等,在这里就不一一介绍了,大家去看官方文档吧。
  用 NSCodition 同步执行的顺序
  NSCodition 是一种特殊类型的锁,我们可以用它来同步操作执行的顺序。它与 mutex 的区别在于更加精准,等待某个 NSCondtion 的线程一直被 lock,直到其他线程给那个 condition 发送了信号。下面我们来看使用示例:
   某个线程等待着事情去做,而有没有事情做是由其他线程通知它的。
[cocoaCondition lock];
while (timeToDoWork <= 0)
    [cocoaCondition wait];
 
timeToDoWork--; 
// Do real work here.
[cocoaCondition unlock];

其他线程发送信号通知上面的线程可以做事情了:
[cocoaCondition lock];
timeToDoWork++;
[cocoaCondition signal];
[cocoaCondition unlock];

线程间通信
   线程在运行过程中,可能需要与其它线程进行通信。我们可以使用 NSObject 中的一些方法:
   在应用程序主线程中做事情:
  
performSelectorOnMainThread:withObject:waitUntilDone:
      performSelectorOnMainThread:withObject:waitUntilDone:modes:
在指定线程中做事情:
performSelector:onThread:withObject:waitUntilDone:
performSelector:onThread:withObject:waitUntilDone:modes:
在当前线程中做事情:    
performSelector:withObject:afterDelay:
performSelector:withObject:afterDelay:inModes:

   取消发送给当前线程的某个消息
cancelPreviousPerformRequestsWithTarget:
      cancelPreviousPerformRequestsWithTarget:selector:object:

   如在我们在某个线程中下载数据,下载完成之后要通知主线程中更新界面等等,可以使用如下接口:
- (void)myThreadMainMethod
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    // to do something in your thread job
    ...
    [self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:NO];
    [pool release];
}

RunLoop
   说到 NSThread 就不能不说起与之关系相当紧密的 NSRunLoop。Run loop 相当于 win32 里面的消息循环机制,它可以让你根据事件 / 消息(鼠标消息,键盘消息,计时器消息等)来调度线程是忙碌还是闲置。
   系统会自动为应用程序的主线程生成一个与之对应的 run loop 来处理其消息循环。在触摸 UIView 时之所以能够激发 touchesBegan/touchesMoved 等等函数被调用,就是因为应用程序的主线程在 UIApplicationMain 里面有这样一个 run loop 在分发 input 或 timer 事件。
   

ios – NSThread gtm_performBlock错误

ios – NSThread gtm_performBlock错误

我正在尝试在Google Maps SDK for iOS文档中运行街景示例,并收到以下错误:

`-[NSThread gtm_performBlock:]: unrecognized selector sent to instance 0x1d55d1f0.
*** Terminating app due to uncaught exception ‘NSinvalidargumentexception’,reason: ‘-[NSThread gtm_performBlock:]: unrecognized selector sent to instance 0x1d55d1f0’.
libc++abi.dylib: terminate called throwing an exception.

奇怪的是,我可以让街景视图在某些项目中工作而不是其他项目.我已经尝试了Google 1.4.3和1.4.2框架,但仍然遇到此错误.知道是什么原因引起的吗?

解决方法

选择项目而不是特定目标,然后打开“构建设置”选项卡:

– 在Other Linker Flags部分中,添加-ObjC.如果看不到这些设置,请将“构建设置”栏中的过滤器从“基本”更改为“全部”.

资源:
https://developers.google.com/maps/documentation/ios/start#getting_the_google_maps_sdk_for_ios

ios – 使用[NSThread sleep:]解决死锁问题

ios – 使用[NSThread sleep:]解决死锁问题

我只是“解决”了似乎是死锁或同步问题:

[NSThread sleepForTimeInterval:0.1];

在一个应用程序中,将来自IPOD库的MPMediaItem(音乐/图像)属性引用附加到对象实例,并通过CoreData对这些对象进行反向存储.我的兴趣是要准确了解发生了什么,以及在这种情况下最佳做法是什么.开始:

每次复制此内容的方法如下:

>用户创建一个新项目.

doc = [[UIManagedDocument alloc] initWithFileURL:docURL];

if (![[NSFileManager defaultManager] fileExistsAtPath:[docURL path]]) {
    [doc savetoURL:docURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
    if (success) {
        completionBlock(doc);
    }
    else {
        DLog(@"Failed document creation: %@",doc.localizedname);
    }
}];

>稍后,managedobjectContext用于关联对象实例并对CoreData模型进行水合

TheProject *theProject = [TheProject projectWithInfo:theProjectInfo
                              inManagedobjectContext:doc.managedobjectContext];

>用户稍后创建“CustomAction”对象,向其添加“ChElement”并将“MusicElement”与ChElement相关联. (这些是CoreData模型对象的假名). MusicElement通过IPOD库添加.

#define PLAYER [MPMusicPlayerController iPodMusicPlayer]

>用户保存此项目,然后切换到已创建一个CustomAction对象的现有项目,其中包含ChElement和MusicElement.
>用户从tableView中选择该ChElement并导航到detailView.
当导航离开ChElementTVC(类似于Apple文档中的CoreData TableViewController类的子类)时,这是必需的:

- (void)viewWilldisappear:(BOOL)animated
{
    [super viewWilldisappear:animated];
    self.fetchedResultsController.delegate = nil;
}

>在详细信息视图中,用户更改ChElement对象的属性并保存项目. detailView调用其委托(ChElementTVC)来进行保存.保存是保存NSManagedobject的UIManagedDocument实例.

#define SAVEDOC(__DOC__) [ProjectDocumentHelper saveProjectDocument:__DOC__]

// Delegate

- (void)chAddElementDetailViewController:(ChDetailViewController *)sender didPressSaveButton:(Nsstring *)message
{
    SAVEDOC(THE_CURRENT_PROJECT_DOCUMENT);

    [self.navigationController popViewControllerAnimated:YES];
 }


// Helper Class

+ (void)saveProjectDocument:(UIManagedDocument *)targetDocument
{
    NSManagedobjectContext *moc = targetDocument.managedobjectContext;
    [moc performBlockAndWait:^{
        DLog(@" Process Pending Changes before saving : %@,Context = %@",targetDocument.description,moc);

        [moc processpendingChanges];
        [targetDocument savetoURL:targetDocument.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:NULL];
    }];
}

>由于委托(ChElementTVC)从导航堆栈弹出detailView,
调用其viewWillAppear,并恢复fetchedResultsController.delegate.

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if (!self.fetchedResultsController.delegate) {

        DLog(@"Sleep Now %@",self);

        //http://mobiledevelopertips.com/core-services/sleep-pause-or-block-a-thread.html

       [NSThread sleepForTimeInterval:0.1];

       DLog(@"Wake up %@",self);

       [self fetchedResultsControllerWithPredicate:_savedPredicate]; // App Hangs Here ... This is sending messages to CoreData objects.

       [self.tableView reloadData];
}

没有[NSThread sleepForTimeInterval:0.1];该应用程序挂起.当我通过Xcode发送SIGINT时,我得到调试器并显示以下内容:

(lldb)bt

* thread #1: tid = 0x1c03,0x30e06054 libsystem_kernel.dylib semaphore_wait_trap + 8,stop reason = signal SIGINT
    frame #0: 0x30e06054 libsystem_kernel.dylib semaphore_wait_trap + 8
    frame #1: 0x32c614f4 libdispatch.dylib _dispatch_thread_semaphore_wait$VARIANT$mp + 12   
    frame #2: 0x32c5f6a4 libdispatch.dylib _dispatch_barrier_sync_f_slow + 92   
    frame #3: 0x32c5f61e libdispatch.dylib dispatch_barrier_sync_f$VARIANT$mp + 22
    frame #4: 0x32c5f266 libdispatch.dylib dispatch_sync_f$VARIANT$mp + 18
    frame #5: 0x35860564 CoreData _perform + 160

(lldb)帧选择5

frame #5: 0x35860564 CoreData _perform + 160
    CoreData _perform + 160:
    -> 0x35860564:  add    sp,#12
       0x35860566:  pop    {r4,r5,r7,pc}

    CoreData -[NSManagedobjectContext(_nestedContextSupport) executeRequest:withContext:error:]:
       0x35860568:  push   {r4,r6,lr}
       0x3586056a:  add    r7,sp,#12

(lldb)反汇编-f

CoreData _perform:
        0x358604c4:  push   {r4,lr}

    ... snipped ...

        0x35860560:  blx    0x35938bf4                ; symbol stub for: dispatch_sync_f

    -> 0x35860564:  add    sp,pc}

另一种解决方法是可行的.在 – [ChElementTVC viewDidAppear:]中编码fetchedResultsController.delegate恢复也有效地延迟了主队列上的此设置.

另一种解决方法是在项目保存完成后在完成块中执行导航弹出:

#define SAVEDOCWITHCOMPLETION(__DOC__,__COMPLETION_BLOCK__)[ProjectDocumentHelper saveProjectDocument:__DOC__ completionHandler:__COMPLETION_BLOCK__]

    void (^completionBlock)(BOOL) = ^(BOOL success) {
        [self.navigationController popViewControllerAnimated:YES];
    };

    SAVEDOCWITHCOMPLETION(THE_CURRENT_PROJECT_DOCUMENT,completionBlock);

我认为保存操作在后台与主队列上的委托恢复同时运行,但我不知道如何检查/证明/反驳该理论.

那么,有人可以解释发生了什么,在这种情况下最好的做法是什么?此外,赞赏研究参考.

解决方法

我最终实现了第三种方法,即使用完成块保存文档以序列化与CoreData存储交互的事务.

IOS 之多线程

IOS 之多线程

多线程 GCD 

分为:主队列、全局队列、自定义队列

dispatch_get_mian_queue

dispatch_get_global_queue

dispatch_queue_create

dispatch_async

dispatch_sync

dispatch_queue_concurrent

dispatch_queue_serial

在 swift 中队列的前缀均是是 dispatch 开头,如果创建一个队列,可以如下创建

  let create_queue:dispatch_queue_tdispatch_queue_create("a",DISPATCH_QUEUE_CONCURRENT)

let main:dispatch_queue_t =  dispatch_get_main_queue()

let global_queue:dispatch_queue_t =  dispatch_get_global_queue(0,0)

在创建全局队列时,有两个参数需要进行设置,第一个用于设置 ID,标志 queue,第二个用于设置队列的优先级,有四种用于选择

func dispatch_get_global_queue(identifier: Int, _ flags: UInt) -> dispatch_queue_t!

@param identifier

 * A quality of service class defined in qos_class_t or a priority defined in

 * dispatch_queue_priority_t.

 *

 * It is recommended to use quality of service class values to identify the

 * well-known global concurrent queues:

 *  - QOS_CLASS_USER_INTERACTIVE

 *  - QOS_CLASS_USER_INITIATED

 *  - QOS_CLASS_DEFAULT

 *  - QOS_CLASS_UTILITY

 *  - QOS_CLASS_BACKGROUND

 * The global concurrent queues may still be identified by their priority,

 * which map to the following QOS classes:

 *  - DISPATCH_QUEUE_PRIORITY_HIGH:         QOS_CLASS_USER_INITIATED

 *  - DISPATCH_QUEUE_PRIORITY_DEFAULT:      QOS_CLASS_DEFAULT

 *  - DISPATCH_QUEUE_PRIORITY_LOW:          QOS_CLASS_UTILITY

 *  - DISPATCH_QUEUE_PRIORITY_BACKGROUND:   QOS_CLASS_BACKGROUND


用户可以自行创建队列,并设置该队列是串行队列还是并行队列

let create_queue:dispatch_queue_t =  dispatch_queue_create("a",DISPATCH_QUEUE_CONCURRENT

let create_queue:dispatch_queue_t =  dispatch_queue_create("a",DISPATCH_QUEUE_SERAIL) 



另外一种情况: 

如果一个应用需要串行队列,并行任务,就需要设置代码

 方案:设置并行队列,任务设置成同步,这样就使任务被串行执行,代码参考如下:

  let create_queue:dispatch_queue_tdispatch_queue_create("a",DISPATCH_QUEUE_CONCURRENT)

        dispatch_sync(create_queue) { () -> Void in

            for(var i:integer_t = 0; i < 5 ;i++){

                print("create_queue1 ")

            }

            

        }

        

        dispatch_sync(create_queue) { () -> Void in

            for(var i:integer_t = 0; i < 5 ;i++){

                print("create_queue2 ")

            }

            

        }





附录:整个 GCD 代码参考

//

//  ViewController.swift

//  GCD

//

//  Created by WHJ on 16/1/18.

//  Copyright © 2016 WHJ. All rights reserved.

//


import UIKit


class ViewController: UIViewController {


    

    // 多线程

    

    

    var btn:UIButton?

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        

        print("test.....")

        

        btn = UIButton(frame: CGRect(x: 100, y: 100, width: 200, height: 40))

        btn?.backgroundColor = UIColor.redColor()

        btn?.setTitle("Click Me", forState: UIControlState.Normal)

        btn?.addTarget(self, action: "testGCD:", forControlEvents: UIControlEvents.TouchUpInside)

//        btn?.addTarget(<#T##target: AnyObject?##AnyObject?#>, action: Selector, forControlEvents: <#T##UIControlEvents#>)

        

        

        

        

        self.view.addSubview(btn!)

    }


    func testGCD(sender:UIButton){

        print("start test GCD")

        //first create  a queue task

        /*GCD offers three kinds of  queues

            main : tasks execute serially on your application''s main thread

            concurrent: tasks are dequeued in FIFO order,but run concurrently and can finish in any order

            serial:tasks execute one at a time in FIFO order

        */

        

        //calling main_queue

//        let main:dispatch_queue_t =  dispatch_get_main_queue()

//        dispatch_async(main) { () -> Void in

//            for(var i:integer_t = 0; i < 5 ;i++){

//                 print("\(main) value : \(i)")

//            }

//            for(var j:integer_t = 0; j < 5 ;j++){

//                print("\(main) value : \(j)")

//            }

//


        let global_queue:dispatch_queue_tdispatch_get_global_queue(0,0)

//        dispatch_async(global_queue) { () -> Void in

//            for(var i:integer_t = 0; i < 5 ;i++){

//            print("global_queue1 value : \(i)")

//            }

//        

//            }

//        dispatch_async(global_queue) { () -> Void in

//            for(var i:integer_t = 0; i < 5 ;i++){

//                print("global_queue2 value : \(i)")

//            }

//            

//        }

        //

//        let create_queue:dispatch_queue_t =  dispatch_queue_create("a",DISPATCH_QUEUE_SERIAL)

        let create_queue:dispatch_queue_tdispatch_queue_create("a",DISPATCH_QUEUE_CONCURRENT)

        dispatch_async(create_queue) { () -> Void in

            for(var i:integer_t = 0; i < 5 ;i++){

                print("create_queue1 ")

            }

            

        }

        

        dispatch_async(create_queue) { () -> Void in

            for(var i:integer_t = 0; i < 5 ;i++){

                print("create_queue2 ")

            }

            

        }

        

        }

        

 

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }



}








关于iOS 之多线程 NSThreadios多线程nsoperation的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于iOS multiple threads(1)-----NSThread、ios – NSThread gtm_performBlock错误、ios – 使用[NSThread sleep:]解决死锁问题、IOS 之多线程等相关知识的信息别忘了在本站进行查找喔。

本文标签: