44#include " mlx/backend/gpu/available.h"
55#include " mlx/backend/gpu/eval.h"
66#include " mlx/backend/metal/device.h"
7+ #include " mlx/backend/metal/thread_safey.h"
78#include " mlx/backend/metal/utils.h"
89#include " mlx/primitives.h"
910#include " mlx/scheduler.h"
1011
1112namespace mlx ::core::gpu {
1213
14+ std::mutex metal_operation_mutex;
15+
1316bool is_available () {
1417 return true ;
1518}
@@ -30,6 +33,7 @@ inline void check_error(MTL::CommandBuffer* cbuf) {
3033}
3134
3235void eval (array& arr) {
36+ std::lock_guard<std::mutex> lock (metal_operation_mutex);
3337 auto pool = metal::new_scoped_memory_pool ();
3438 auto s = arr.primitive ().stream ();
3539 auto & d = metal::device (s.device );
@@ -78,6 +82,7 @@ void eval(array& arr) {
7882}
7983
8084void finalize (Stream s) {
85+ std::lock_guard<std::mutex> lock (metal_operation_mutex);
8186 auto pool = metal::new_scoped_memory_pool ();
8287 auto & d = metal::device (s.device );
8388 auto cb = d.get_command_buffer (s.index );
@@ -88,6 +93,7 @@ void finalize(Stream s) {
8893}
8994
9095void synchronize (Stream s) {
96+ std::lock_guard<std::mutex> lock (metal_operation_mutex);
9197 auto pool = metal::new_scoped_memory_pool ();
9298 auto & d = metal::device (s.device );
9399 auto cb = d.get_command_buffer (s.index );
0 commit comments