1

I'm writing a Java program that uses a hardware driver written in c. This hardware driver starts a callback thread, and you can register callback functions to be called when stuff happens. How can I attach this thread to the jvm so that it can call the Java methods for these callbacks? I only have the thread id returned from the start_callbacks() function, returned as an int, but it is the pthread_t used in the call to pthread_create().

One way I found is to use pthread_once on the start of every callback function and attach the thread there. But then there is no way to detach it. I tried to use pthread_cleanup_push/pop, but they need to be called as a pair so that didn't work.

It seems to me that my only option to do this right is to attach and detach the thread at every callback call. Or rewrite the driver somewhat, which I really don't want to do.

Is there something I missed?

liei
  • 11
  • 1
  • This is probably unhelpful, but have you considered implementing the program in C, and using System.exec or something to connect it to Java? Your current approach seems technically risky to me. – Stephen C Apr 06 '12 at 02:38

2 Answers2

2

That's exactly what the JNI calls AttachCurrentThread() and DetachCurrentThread() are for.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Yes I know. But i don't create the thread myself, so how do I get the thread to call AttachCurrenThread and DetachCurrentThread? The only code I can get the thread to execute is the callback functions. – liei Apr 06 '12 at 08:50
  • You don't need the 'thread to call `AttachCurrentThread()`'. It attaches the current thread. That's why it's called `AttachCurrentThread()`. Obviously you have to call these methods inside the callback functions. – user207421 Apr 06 '12 at 09:36
  • I know that that's a solution to the problem, attaching and detaching every time a callback is made. But I was hoping there was a way to get the thread to call AttachCurrentThread and DetachCurrentThread at appropriate times, just once. So that I don't need to attach the thread every time a callback is made. I might be overestimating how costly attaching the thread is, the frequency of callbacks are a couple a second, so it might not be a problem. I would just have preferred to attach and detach the thread once, is the correct way of doing this to attach and detach every time a call is made? – liei Apr 06 '12 at 11:27
  • @leie I would get it working first and then evalute. But half a second is forever in computing. – user207421 Apr 06 '12 at 11:50
0

The solution to you problem can be resolved with thread_local storage (C++ 11 and higher). This allows you to attach to an arbitrary thread, and then it will automatically detach when the thread exist (even when you didn't create the thread and have no control over it's life cycle).

A sample example of how to implement that in C++ can be found in my answer here: https://stackoverflow.com/a/59934966/8367574

Gideon Gyabaah
  • 388
  • 2
  • 7