iOS轻量级多线程实现

之前两片文章分别讲了GCD和NSOperation, 这里再简单说一下轻量级的多线程NSThread和POSIX Thread。
(一)、NSThread
两种方式创建NSThread, 一种调用类方法,直接启动线程
[NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:nil];
一种是new 一个NSThread的对象,然后调用start启动
NSThread* myThread = [[NSThread alloc] initWithTarget:self
selector:@selector(test:)
object:nil];
[myThread start];
如果拥有某个正在运行的NSThread对象实例,那么可以通过performSelector:onThread:withObject:waitUntilDone:进行线程间通信,但是最好不要做耗时或者很频繁的通信。
NSObject的类方法 performSelectorInBackground:withObject: 也可以创建一个线程:
[Obj performSelectorInBackground:@selector(doSomething) withObject:nil];
当然也就存在:
[Obj performSelectorOnMainThread:@selector(doSomething) withObject:nil waitUntilDone:NO;

(二)、POSIX Threads
使用POSIX API编写多线程将使得之后的跨平台比较容易。这里只给出一个例子参考(例子来源苹果官方文档)
.#include “assert.h”
.#include “pthread.h”
void* PosixThreadMainRoutine(void* data)
{
// Do some work here
return NULL;
}
void LaunchThread()
{
// Create the thread using POSIX routines.
pthread_attr_t attr;
pthread_t posixThreadID;
int returnVal;
returnVal = pthread_attr_init(&attr);
assert(!returnVal);
returnVal = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
assert(!returnVal);
int threadError = pthread_create(&posixThreadID, &attr, &PosixThreadMainRoutine, NULL);
returnVal = pthread_attr_destroy(&attr);
assert(!returnVal);
if (threadError != 0)
{
// Report an error.
}
}

你可能感兴趣的:(iOS学习,多线程,ios)