Using Win32 API functionality along with/from pthreads
I have my own threading library built using TinyThread++. It works quite well, and it was also a great learning experience for me. I have my own datastructures for passing around messages, and the interface makes good sense to me, primarily because I was its author.
Whenever a thread is created in my system, it runs in a loop, and checks for messages occasionally via a message passing protocol of my own devising.
Now I want to start using some Windows API functionality, and windows has its own set of conventions and message queues, etc. Now I'm pretty sure that TinyThread++ uses pthreads. Since I'm using MinGW, I'm wondering if pthreads is being implemented on windows threads. If this is the case, I may be able to just treat my pthreads-threads as windows-threads. But if not, I suspect开发者_如何转开发 I might run into some strange behavior.
edit: looking at the thread
type given by Tinythread++ it looks like it actually uses the windows HANDLE
to keep track of the threads and even uses _beginthreadex
to spawn them.
My question is, will Windows be happy if I go around calling SetWindowsHookEx
from some point in my pthreads code? I realize I need to have a Windows message polling loop in the same thread. I intend to do something like this:
try {
HHOOK mousehook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc,
NULL, 0);
if (mousehook == NULL) printf("Mousehook error %u\n",GetLastError());
while(true) {
MSG msg;
if (GetMessage(&msg,0,0,0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
UnhookWindowsHookEx(mousehook);
printf("Procedure completed without exceptional events.\n");
} catch (...) {
printf("Exception!\n");
}
That should be fine.
You may run into trouble if you try to pass pthread thread ids to Windows threading functions which want a thread HANDLE, but here you just need the loop to stay in the same thread as SetWindowsHookEx
.
Pthreads don't exist on windows, unless you're using something like cygwin. Either way, the API docs say SetWindowsHookEx associates hooks for application events tied to a particular thread, OR to the desktop on which your app is running. So it can handle being called in a thread, but you need to read the docs so that you call it in a way that gives you the ehavior you want.
精彩评论