c++ - SSL 读取和 SSL 同时写入

标签 c++ multithreading sockets ssl

我有两个线程,mainThreadrecvThread

recvThread 上,我调用了 SSL_read(ssl, readBuffer, sizeof(readBuffer))。这会阻塞线程,直到接收到数据。

然后,在 mainThread 上,我被告知需要发送一些数据。因此,我调用了 SSL_write(ssl, someData, sizeof(someData))

有时,这工作正常。其他时候,这会失败并出现奇怪的内部错误消息。我的猜测是,当在同一 ssl 上下文中发生 SSL_read 时,我无法调用 SSL_write。这对我来说很有意义,但我该如何解决呢?

我是否让 recvThread 做类似的事情:

SSL * ssl;
std::string data;
boost::mutex dataMutex;

while (recvThreadShouldBeRunning) {
    char readBuffer[100];
    auto nRead = SSL_read(ssl, readBuffer, sizeof(readBuffer)); //Non-blocking call to SSL_read.

    // Do something with nRead (handle errors, use data)

    {
        auto dataLock = boost::unique_lock<boost::mutex>(dataMutex);
        if (data.length() > 0)
        {
            SSL_write(ssl, data.c_str(), data.length());
        }
    }
    sleep(50);
}

然后当我需要发送一些东西时...

{
    auto dataLock = boost::unique_lock<boost::mutex>(dataMutex);
    data = "some data";
}

这似乎可行,但我认为这对我的问题来说是一个相当丑陋的解决方案。有没有办法以某种方式SSL_lock() SSL_wait_on_data() SSL_unlock()?或者这是解决问题的最佳方法?

解决这类问题的标准方法是什么?

感谢您的宝贵时间。

最佳答案

文档中的引述似乎包含了答案:

OpenSSL can safely be used in multi-threaded applications provided that at least two callback functions are set, locking_function and threadid_func.

locking_function(int mode, int n, const char *file, int line) is needed to perform locking on shared data structures. (Note that OpenSSL uses a number of global data structures that will be implicitly shared whenever multiple threads use OpenSSL.) Multi-threaded applications will crash at random if it is not set.

locking_function() must be able to handle up to CRYPTO_num_locks() different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and releases it otherwise.

file and line are the file number of the function setting the lock. They can be useful for debugging.

-- threads - OpenSSL.

The example of using the locking-related functions (github) :

crypto/threads/mttest.c shows examples of the callback functions on Solaris, Irix and Win32.

-- threads - OpenSSL.

关于c++ - SSL 读取和 SSL 同时写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21527206/

相关文章:

java - tomcat 7 + freebsd 7.2(32 位)多线程应用程序抛出 OutOfMemoryError : could not create native thread

python套接字协议(protocol)不支持

c++ - 来自两个不同文件的关联值

c++ - 如何在没有无限循环的情况下使用 CMake 的 add_subdirectory

.net - Akka.Net 和缓存一致性

C# (mono) 没有利用所有内核

c++ - 在哪些情况下 __declspec( align( # ) ) 不能工作?

c++ - 如何遍历图形并沿途提取边缘权重?

c++ - 使用 Qt/C++ 等到所有线程在主线程中完成

python - socket.shutdown 与 socket.close