libssh2 库使用openssl 加密时,要设置以下加锁回调(可以参见openssl 中mtest.c代码),另外一个更重要应注意地方是包含头文件时,一定要定义重要的宏(OPENSSL_THREAD_DEFINES),否则加锁回调无效,导致无法在多线程环境当中使用
#include <openssl/buffer.h>
#include <openssl/crypto.h>
#define OPENSSL_THREAD_DEFINES
#include <openssl/opensslconf.h>
#if defined(OPENSSL_THREADS)
#include <pthread.h>
#endif
static pthread_mutex_t
static long *lock_count;
extern "C" unsigned long pthreads_thread_id()
{
unsigned long ret;
ret=(unsigned long)pthread_self();
return(ret);
}
extern "C" void pthreads_locking_callback(int mode, int type, const char *file, int line)
{
//DLOG_DEBUG("pthreads_locking_callback");
if (mode & CRYPTO_LOCK)
{
pthread_mutex_lock(&(lock_cs[type]));
lock_count[type]++;
}
else
{
pthread_mutex_unlock(&(lock_cs[type]));
}
}
extern "C" int thread_setup()
{
int i = 0;
lock_cs = (pthread_mutex_t*)malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
lock_count = (long *)malloc(CRYPTO_num_locks() * sizeof(long));
for(i =0; i<CRYPTO_num_locks(); i++)
{
lock_count[i]=0;
pthread_mutex_init(&(lock_cs[i]),NULL);
}
CRYPTO_set_id_callback(pthreads_thread_id);
CRYPTO_set_locking_callback(pthreads_locking_callback);
return 0;
}