Memory leaks and seg faults when using OpenMP and OpenSSL

前端 未结 1 1588
渐次进展
渐次进展 2020-12-20 01:37

I have a huge code (its my school project) where I use Openssl. Everything was working perfeclty, util I decided I will go multithreaded. I chose openmp

1条回答
  •  醉梦人生
    2020-12-20 02:36

    Take a look at the example openssl/crypto/threads/mttest.c in the OpenSSL source code tree. Basically, you have to provide two callback functions:

    • one that implements locking and unlocking and
    • one that returns a unique thread ID.

    Both are easily implemented using OpenMP:

    omp_lock_t *locks;
    
    // Locking callback
    void openmp_locking_callback(int mode, int type, char *file, int line)
    {
      if (mode & CRYPTO_LOCK)
      {
        omp_set_lock(&locks[type]);
      }
      else
      {
        omp_unset_lock(&locks[type]);
      }
    }
    
    // Thread ID callback
    unsigned long openmp_thread_id(void)
    {
      return (unsigned long)omp_get_thread_num();
    }
    

    Before you start, the locks have to be initialised and callbacks set:

    void openmp_thread_setup(void)
    {
      int i;
    
      locks = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(omp_lock_t));
      for (i=0; i

    You should call openmp_thread_setup() once in your program somewhere before the first parallel region and you should call openmp_thread_cleanup() once after the last parallel region:

    // Program start
    
    openmp_thread_setup();
    
    #pragma omp parallel
    {
       // Parallel OpenSSL calls are now data race free
    }
    
    #pragma omp parallel
    {
       // Parallel OpenSSL calls are now data race free
    }
    
    #pragma omp parallel
    {
       // Parallel OpenSSL calls are now data race free
    }
    
    openmp_thread_cleanup();
    
    // Program should end now
    

    0 讨论(0)
提交回复
热议问题