Skip to main content
 首页 » 编程设计

C++经典案例

2022年07月19日31cmt

1. per-thread的单例模式

//单例子模式,per-thread的单例模式 
IPCThreadState* IPCThreadState::self() //IPCThreadState.cpp 
{ 
    if (gHaveTLS.load(std::memory_order_acquire)) { 
restart: 
        const pthread_key_t k = gTLS; 
        IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k); 
        if (st) return st; 
        return new IPCThreadState; 
    } 
 
    // Racey, heuristic test for simultaneous shutdown. 
    if (gShutdown.load(std::memory_order_relaxed)) { 
        ALOGW("Calling IPCThreadState::self() during shutdown is dangerous, expect a crash.\n"); 
        return nullptr; 
    } 
 
    pthread_mutex_lock(&gTLSMutex); 
    if (!gHaveTLS.load(std::memory_order_relaxed)) { 
        int key_create_value = pthread_key_create(&gTLS, threadDestructor); 
        if (key_create_value != 0) { 
            pthread_mutex_unlock(&gTLSMutex); 
            ALOGW("IPCThreadState::self() unable to create TLS key, expect a crash: %s\n", 
                    strerror(key_create_value)); 
            return nullptr; 
        } 
        gHaveTLS.store(true, std::memory_order_release); 
    } 
    pthread_mutex_unlock(&gTLSMutex); 
    goto restart; 
}

本文参考链接:https://www.cnblogs.com/hellokitty2/p/16463356.html