线程创建和休眠唤醒耗时对比

线程创建对比

A16,iOS 26 单位:us
pthread_create 97
__workq_kernreturn 94

1. 提交任务,workqueue机制

void dispatch_create_thread() {
    dispatch_queue_t queues[10];
    for (int i = 0; i < 10; i++) {
        queues[i] = dispatch_queue_create("Serial", nullptr);
        dispatch_async(queues[i], ^{
            pthread_setname_np("Other");
            sleep(100);
        });
    }
    sleep(1);
    dispatch_queue_t queue = dispatch_queue_create("Concurrent", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        pthread_setname_np("WorkerThread");
        cpu_intensive_work("test", 1);
    });
    
    sleep(2);
    
    exit(0);
}
Screenshot 2025-09-18 at 19.48.32.png

Screenshot 2025-09-18 at 19.49.00.png

2. 使用pthread_create

Screenshot 2025-09-18 at 19.55.46.png
Screenshot 2025-09-18 at 19.57.59.png

休眠唤醒对比

结果(计算从开始唤醒到runnable开始时间点的时间差)

单位:us A10,iOS15.7 A12,iOS18.5 A16,iOS 26
cv_notify 20 18 6
__workq_kernreturn 26 24 9

1. 使用cv_notify方式

代码

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
bool waited = false;
void* thread_func(void* ptr) {
    pthread_setname_np("WorkerThread");
    pthread_mutex_lock(&mutex);
    waited = true;
    pthread_cond_wait(&cond, &mutex);
    EMIT_EVENT("notify success");
    return nullptr;
}

void thread_notify() {
    sleep(1);
    pthread_t thread;
    pthread_create(&thread, nullptr, thread_func, nullptr);
    while (!waited);
    pthread_mutex_lock(&mutex);
    sleep(1);
   EMIT_EVENT("start notify");
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&mutex);  // 必须释放锁!
    pthread_join(thread, nullptr);
    sleep(1);
    exit(0);
}
Screenshot 2025-09-18 at 14.59.30.png
Screenshot 2025-09-18 at 15.00.20.png

2. gcd任务提交到worker唤醒

void submit_notify() {
    sleep(1);
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), ^{
        pthread_setname_np("WorkerThread1");
        cpu_intensive_work("test", 1);
    });
    
    sleep(2);

    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), ^{
        pthread_setname_np("WorkerThread2");
        cpu_intensive_work("test", 1);
    });
    
    sleep(2);
    
    exit(0);
}
Screenshot 2025-09-18 at 15.13.12.png
Screenshot 2025-09-18 at 14.50.43.png
Screenshot 2025-09-18 at 14.51.12.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。