Using libssh2 in a multi-threaded program/library

本文介绍了解决libssh2在使用OpenSSL或gcrypt作为加密库时遇到的多线程问题的方法。详细解释了如何通过设置锁定回调函数来避免竞态条件,确保在多线程环境下libssh2的稳定运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Whether you use libssh2 when it is compiled against OpenSSL or gcrypt, there's a known issue with multi-threaded programs, even if each session is correctly created and used within a single thread. Specifically, the multi-threading "glue" hooks in the support library need to be managed by the application.

The gcrypt library is documented at http://www.gnupg.org/documentation/manuals/gcrypt/Multi_002dThreading.html

For OpenSSL, the call is CRYPTO_set_locking_callback. An example for Win32 (lifted out of the OpenSSL source file crypto/threads/mttest.c):

/***************************/
/* t h r e a d _ s e t u p */
/***************************/
void thread_setup(void)
{
        int i;

        lock_cs=OPENSSL_malloc(CRYPTO_num_locks() * sizeof(HANDLE));

        for (i=0; i<CRYPTO_num_locks(); i++)
        {
                lock_cs[i]=CreateMutex(NULL,FALSE,NULL);
        }

        CRYPTO_set_locking_callback((void (*)(int,int,const char *,int))win32_locking_callback);
}

/*******************************/
/* t h r e a d _ c l e a n u p */
/*******************************/
void thread_cleanup(void)
{
        int i;

        CRYPTO_set_locking_callback(NULL);

        for (i=0; i<CRYPTO_num_locks(); i++)
        {
                CloseHandle(lock_cs[i]);
        }
        OPENSSL_free(lock_cs);
}

/***********************************************/
/* w i n 3 2 _ l o c k i n g _ c a l l b a c k */
/***********************************************/
void win32_locking_callback(int mode, int type, char *file, int line)
{
        if (mode & CRYPTO_LOCK)
        {
                WaitForSingleObject(lock_cs[type],INFINITE);
        }
        else
        {
                ReleaseMutex(lock_cs[type]);
        }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值