--- md_rand.c.orig	2010-10-08 16:09:56.000000000 +0300
+++ md_rand.c	2010-10-08 15:25:13.000000000 +0300
@@ -224,7 +224,16 @@
 	else
 		do_not_lock = 0;
 
-	if (!do_not_lock) CRYPTO_w_lock(CRYPTO_LOCK_RAND);
+	if (!do_not_lock)
+		{
+		CRYPTO_w_lock(CRYPTO_LOCK_RAND);
+
+		CRYPTO_w_lock(CRYPTO_LOCK_RAND2);
+		locking_thread = CRYPTO_thread_id();
+		CRYPTO_w_unlock(CRYPTO_LOCK_RAND2);
+		crypto_lock_rand = 1;
+		}
+
 	st_idx=state_index;
 
 	/* use our own copies of the counters so that even
@@ -256,7 +265,13 @@
 
 	md_count[1] += (num / MD_DIGEST_LENGTH) + (num % MD_DIGEST_LENGTH > 0);
 
-	if (!do_not_lock) CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
+	if (!do_not_lock)
+		{
+		/* before unlocking, we must clear 'crypto_lock_rand' */
+		crypto_lock_rand = 0;
+
+		CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
+		}
 
 	EVP_MD_CTX_init(&m);
 	for (i=0; i<num; i+=MD_DIGEST_LENGTH)
@@ -299,7 +314,16 @@
 		}
 	EVP_MD_CTX_cleanup(&m);
 
-	if (!do_not_lock) CRYPTO_w_lock(CRYPTO_LOCK_RAND);
+	if (!do_not_lock)
+		{
+		CRYPTO_w_lock(CRYPTO_LOCK_RAND);
+
+		CRYPTO_w_lock(CRYPTO_LOCK_RAND2);
+		locking_thread = CRYPTO_thread_id();
+		CRYPTO_w_unlock(CRYPTO_LOCK_RAND2);
+		crypto_lock_rand = 1;
+		}
+
 	/* Don't just copy back local_md into md -- this could mean that
 	 * other thread's seeding remains without effect (except for
 	 * the incremented counter).  By XORing it we keep at least as
@@ -310,7 +334,13 @@
 		}
 	if (entropy < ENTROPY_NEEDED) /* stop counting when we have enough */
 	    entropy += add;
-	if (!do_not_lock) CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
+	if (!do_not_lock)
+		{
+		/* before unlocking, we must clear 'crypto_lock_rand' */
+		crypto_lock_rand = 0;
+
+		CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
+		}
 	
 #if !defined(OPENSSL_THREADS) && !defined(OPENSSL_SYS_WIN32)
 	assert(md_c[1] == md_count[1]);
