Pavan
Pavan

Reputation: 18548

convert pthread to objective-c

Im trying to convert the following to objective-c code.

This is the current thread I have in C and works fine

//calling EnrollThread method on a thread in C
pthread_t thread_id; 
pthread_create( &thread_id, NULL, EnrollThread, pParams );

//What the EnrollThread method structure looks like in C
void* EnrollThread( void *arg )

What my method structure looks like now that I've changed it to objective-c

-(void)enrollThreadWithParams:(LPBIOPERPARAMS)params;

Now I'm not sure how to call this objective-c method with the pthread_create call. I've tried something like this:

pthread_create( &thread_id, NULL, [refToSelf enrollThreadWithParams:pParams], pParams );

But I believe I have it wrong. Can anyone enlighten me on why this does not work and what it is I need to do to fix it so that I can create my thread in the background? My UI is getting locked until the method finishes what it's doing.

I was thinking of also using dispatch_sync but I haven't tried that.

Upvotes: 0

Views: 1974

Answers (3)

Rob
Rob

Reputation: 438467

The go to reference for concurrent programming is the Concurrency Programming Guide which walks you through dispatch queues (known as Grand Central Dispatch, GCD) and operation queues. Both are incredibly easy to use and offer their own respective advantages.

In their simplest forms, both of these are pretty easy to use. As others have pointed out, the process for creating a dispatch queue and then dispatching something to that queue is:

dispatch_queue_t queue = dispatch_queue_create("com.domain.app", DISPATCH_QUEUE_CONCURRENT);

dispatch_async(queue, ^{
    // something to do in the background
});

The operation queue equivalent is:

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[queue addOperationWithBlock:^{
    // something to do in the background
}];

Personally, I prefer operation queues where:

  • I need controlled/limited concurrency (i.e. I'm going to dispatch a bunch of things to that queue and I want them to run concurrent with respect to not only the main queue, but also with respect to each other, but I don't want more than a few of those running simultaneously). A good example would be when doing concurrent network requests, where you want them running concurrently (because you get huge performance benefit) but you generally don't want more than four of them running at any given time). With an operation queue, one can specify maxConcurrentOperationCount whereas this tougher to do with GCD.

  • I need fine level of control over dependencies. For example, I'm going to start operations A, B, C, D, and E, but B is dependent on A (i.e. B shouldn't start before A finishes), D is dependent upon C, and E is dependent upon both B and D finishing.

  • I need to enjoy concurrency on tasks that, themselves, run asynchronously. Operations offer a fine degree of control over what determines when the operation is to be declared as isFinished with the use of NSOperation subclass that uses "concurrent operations". A common example is the network operation which, if you use the delegate-based implementation, runs asynchronously, but you still want to use operations to control the flow of one to the next. The very nice networking library, AFNetworking, for example, uses operations extensively, for this reason.

On the other hand, GCD is great for simple one-off asynchronous tasks (because you can avail yourself of built-in "global queues", freeing yourself from making your own queue), serial queues for synchronizing access to some shared resource, dispatch sources like timers, signaling between threads with semaphores, etc. GCD is generally where people get started with concurrent programming in Cocoa and Cocoa Touch.

Bottom line, I personally use operation queues for application-level asynchronous operations (network queues, image processing queues, etc.), where the degree of concurrency becomes and important issue). I tend to use GCD for lower-level stuff or quick and simple stuff. GCD (with dispatch_async) is a great place to start as you dip your toe into the ocean of concurrent programming, so go for it.

There are two things I'd encourage you to be aware of, regardless of which of these two technologies you use:

  1. First, remember that (in iOS at least) you always want to do user interface tasks on the main queue. So the common patterns are:

    dispatch_async(queue, ^{
        // do something slow here
    
        // when done, update the UI and model objects on the main queue
    
        dispatch_async(dispatch_get_main_queue(), ^{
            // UI and model updates can go here
        });
    });
    

    or

    [queue addOperationWithBlock:^{
        // do something slow here
    
        // when done, update the UI and model objects on the main queue
    
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            // do UI and model updates here
        }];
    }];
    
  2. The other important issue to consider is synchronization and "thread-safety". (See the Synchronization section of the Threading Programming Guide.) You want to make sure that you don't, for example, have the main thread populating some table view while, at the same time, some background queue is changing the data used by that table view at the same time. You want to make sure that while any given thread is using some model object or other shared resource, that another thread isn't mutating it, leaving it in some inconsistent state.

There's too much to cover in the world of concurrent programming. The WWDC videos (including 2011 and 2012) offer some great background on GCD and asynchronous programming patterns, so make sure you avail yourself of that great resource.

Upvotes: 1

Jody Hagins
Jody Hagins

Reputation: 28419

If you already have working code, there is no reason to abandon pthreads. You should be able to use it just fine.

If, however, you want an alternative, but you want to keep your existing pthread entry point, you can do this easily enough...

dispatch_queue_t queue = dispatch_queue_create("EnrollThread", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
    EnrollThread(parms);
});

Upvotes: 0

Merlevede
Merlevede

Reputation: 8180

In objective C you don't really use pthread_create, although you can still use it, but the thread entry point needs to be a C function, so I'm not sure if this would be the best approach.

There are many options, as you can read in the Threading and Concurrency documents.

  • performSelectorInBackground method of NSObject (and subclasses)
  • dispatch_async (not dispatch_sync as you mentioned)
  • NSOperation and NSOperationQueue
  • NSThread class

I would suggest giving it a shot to the first one, since it is the easiest, and very straightforward, also the second one is very easy because you don't have to create external objects, you just place inline the code to be executed in parallel.

Upvotes: 2

Related Questions