1. 程式人生 > >多執行緒環境下使用openssl

多執行緒環境下使用openssl

static cyg_mutex_t *lock_cs;

// 多執行緒保護的初始化
// This function allocates and initializes the lock array
// and registers the callbacks. This should be called
// after the OpenSSL library has been initialized and
// before any new threads are created.  
void thread_setup(void)
{
    int i;

    // 動態建立 lock 陣列
    // Allocate lock array according to OpenSSL's requirements
    lock_cs=OPENSSL_malloc(CRYPTO_num_locks() * sizeof(cyg_mutex_t));

    // lock 陣列初始化

    // Initialize the locks
    for (i=0; i<CRYPTO_num_locks(); i++)
    {
        cyg_mutex_init(&(lock_cs[i]));
    }

    //  註冊兩個回撥函式
    // Register callbacks
    CRYPTO_set_id_callback((unsigned long (*)())ecos_thread_id_callback);
    CRYPTO_set_locking_callback((void (*)())ecos_locking_callback);
}

// 多執行緒保護的反初始化

// This function deallocates the lock array and deregisters the
// callbacks. It should be called after all threads have
// terminated.  
void thread_cleanup(void)
{
    int i;

    // 清空 locking 回撥函式
    // Deregister locking callback. No real need to
    // deregister id callback.
    CRYPTO_set_locking_callback(NULL);

    // 銷燬初始化時分配的 lock 陣列

    // Destroy the locks
    for (i=0; i<CRYPTO_num_locks(); i++)
    {
        cyg_mutex_destroy(&(lock_cs[i]));
    }