diff --git a/src/c_wrapper/debug.cpp b/src/c_wrapper/debug.cpp
index fbc69c908948b51da033b20c8ee1eb3b91f44d5d..c5806891a2aa00e14fe05725e867ac5a0e9c94fc 100644
--- a/src/c_wrapper/debug.cpp
+++ b/src/c_wrapper/debug.cpp
@@ -4,6 +4,8 @@
 
 namespace pyopencl {
 
+std::mutex dbg_lock;
+
 void
 dbg_print_str(std::ostream &stm, const char *str, size_t len)
 {
diff --git a/src/c_wrapper/debug.h b/src/c_wrapper/debug.h
index 1b8c2ca7bb2a5da7bd1adf0aec0f2de88708f7fe..344914814bbe840b81d5fdcbc8ac3a2f57837945 100644
--- a/src/c_wrapper/debug.h
+++ b/src/c_wrapper/debug.h
@@ -1,6 +1,7 @@
 #include "wrap_cl.h"
 #include "function.h"
 #include <string.h>
+#include <mutex>
 
 #ifndef __PYOPENCL_DEBUG_H
 #define __PYOPENCL_DEBUG_H
@@ -16,6 +17,8 @@ extern bool debug_enabled;
 
 #define DEBUG_ON (PYOPENCL_EXPECT(debug_enabled, DEFAULT_DEBUG))
 
+extern std::mutex dbg_lock;
+
 void dbg_print_str(std::ostream&, const char*, size_t);
 static PYOPENCL_INLINE void
 dbg_print_str(std::ostream &stm, const char *str)
diff --git a/src/c_wrapper/error.h b/src/c_wrapper/error.h
index dfe4654e79ae3a59044b781ffbfeafc336d0bad1..9efb7de32d23b954d46e03d69357850867ad6e28 100644
--- a/src/c_wrapper/error.h
+++ b/src/c_wrapper/error.h
@@ -26,6 +26,7 @@ public:
         : std::runtime_error(msg), m_routine(rout), m_code(c)
     {
         if (DEBUG_ON) {
+            std::lock_guard<std::mutex> lock(dbg_lock);
             std::cerr << rout << ";" << msg<< ";" << c << std::endl;
         }
     }
@@ -186,6 +187,7 @@ public:
     {
         auto res = this->template call<__CLArgGetter>(func);
         if (DEBUG_ON) {
+            std::lock_guard<std::mutex> lock(dbg_lock);
             _print_trace(res, name);
         }
         return res;