Win32多线程下使用libssh2
多线程环境下使用openssl ,必须注册两个回调函数,博主我最近写东西走了不少坑,总结下,希望对以后的人有所帮助。
参考 http://www.cnblogs.com/syru/articles/3036151.html 后,发现不能在win上用。需要做一些更改。
pthread_win32下的 pthread_t与posix的pthread_t的不同。参考文章:http://www.cnblogs.com/ayanmw/archive/2012/08/07/2626661.html
修改后:
#include "libssh2.h" #pragma comment(lib, "pthreadVC2.lib") #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; static pthread_mutex_t *lock_cs; extern "C" unsigned long pthreads_thread_id() { unsigned long ret; ret=(unsigned long)pthread_self().x; 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; }
pthread头文件 下载:
http://download.csdn.net/download/helianthus_/9764005
openssl头文件 下载:
http://download.csdn.net/download/yaojingkao/9673763
然后会有这个错误:
pthread.h(320): error C2011: “timespec”:“struct”类型重定义
把pthread.h定义结构体的那行注释掉就可以了。
最后在你应用程序初始化的地方加上:
lock_cs = (pthread_mutex_t *)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t)); lock_count = (long *)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long)); for (int i = 0; i<CRYPTO_num_locks(); i++) { lock_count[i] = 0; pthread_mutex_init(&(lock_cs[i]), NULL); } 参考文章:http://bbs.csdn.net/topics/391029620 给的有用的连接都是CSDN的,CSDN应该不会比我的博客先挂,就懒的搬运具体的操作内容到文章里了。早点回家睡觉了。