Listing 6–3. POSIX Thread#include <assert.h>
#include <pthread.h>
void* ThreadMethod(void* data){
// Your main logic comes here.
return NULL;
}
void LaunchThread(){
// Create the thread using POSIX routines.
pthread_attr_t attr;
pthread_t posixThreadID;
int returnVal;
// init and check if init a new thread successful
returnVal = pthread_attr_init(&attr);
assert(!returnVal);
// set attribute detach state for new thread
returnVal = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
assert(!returnVal);
// create and run the new thread
int threadError = pthread_create(&posixThreadID, &attr, &ThreadMethod, NULL);
returnVal = pthread_attr_destroy(&attr);
assert(!returnVal);
if (threadError != 0)
{
// Report an error.
}
}
NSObject
所有的对象都可以创建和detach一个新的线程来执行这些对象的selectors。你可以使用下面的这行代码在后台线程中运行doSomething方法:
[myObj performSelectorInBackground:@selector(doSomething) withObject:nil];