0

I've added a C++ file to my project written in Swift. It only calculates some random numbers and also uses an vector array. It's wrapper is written in Objective-C. When I try to call functions from the cpp file the App crashes after some time. But there's a strange behavior, because it doesn't crash while executing the C++ code (it runs like I expect to), but when I load a navigation controller. This hasn't to do anything with either. The console shows this:

'pthread_mutex_lock(&mutex)' failed with error 'EINVAL'(22)

I googled this bug, but I don't really understand the problem in my case.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Josef Büttgen
  • 131
  • 2
  • 12

1 Answers1

1

Because you're using threaded code - the pthreads - the "crashes after some time" makes sense. I suspect it IS running the C++ code: your Swift code calls some Objective-C++ wrapper code, which calls some C++, which spawns a thread, and then returns back to you and you get the data at a later time somehow.

If I were you I'd look at the C++ threading code. There's a Stackoverflow answer that might be relevant here: EINVAL on pthread_mutex. Maybe there's a bug, or the C++ code fails because it assumes Linux and you're on macOS, or something.

I also almost hate to suggest this, but depending on the size/complexity of the C++ maybe it makes sense to just rewrite it in Swift. You're going through a lot of bridging layers to call this code, feels like it could be kind of fragile (which may explain what you're seeing).

(OR compile the C++ as a separate helper app and use cross-communication like XPC or just NSTask to talk back and forth from your C++ process to your Swift process)

Community
  • 1
  • 1
RyanWilcox
  • 13,890
  • 1
  • 36
  • 60