I read on stackoverflow that when using the Windows API to start a thread _beginthreadex() is preferred over CreateThread().
I am creating threads like this using CreateThread():
DWORD WINAPI ThreadFunc(void* data)
{
// code for the thread functionality.
}
HANDLE Multicast = CreateThread(NULL, 0, ThreadFunc, NULL, 0, NULL);
if (Multicast) { } // thread started successfully.
How do I do this with _beginthreadex() rather than CreateThread()?
Can anyone post an example?
_beginthreadex(NULL, 0, ThreadFunc, NULL,0,NULL);
should do the trick for you. You can ignore those additional parameters as most of those are optional.
The following SO links might be useful for you:
Windows threading: _beginthread vs _beginthreadex vs CreateThread C++
_beginthread vs CreateThread
Related
I created a DLL that is running 3 worker threads, and the main thread is in a loop waiting for the threads to complete. The threads get created, but no execution to the threads is done.
I have tried setting MessageBox functions inside the function that gets created with CreateThread() but the box does not appear. I have also tried to debug and the return value from CreateThread() is valid so the thread gets created.
BOOL WINAPI DllMain() {
main();
return 1;
}
int main() {
HANDLE h1, h2, h3;
h1 = CreateThread(first)...
h2 = CreateThread(second)...
h3 = CreateThread(third)...
WaitForSingleObject(h3, INFINITE);
return 1;
}
first() {
MessageBoxA("print some stuff");
return;
}
I have included some pseudocode of what my layout looks like. I am unable to provide the real code due to the sensitivity of it. However this is what is happening. I use LoadLibrary in another project that loads this .DLL. The DLL gets loaded and DllMain is executed. It then calls my main function which creates 3 threads. Each thread is created. But what is inside of the thread does not execute.
EDIT:
// dllmain.cpp : Defines the entry point for the DLL application.
#include <Windows.h>
void mb() {
MessageBoxW(0, L"AAAAAAAAAAAAAAAAAAAAAAAAA", L"AAAAAAAAAAAAAAAAAAAAAAa", 1);
}
void create() {
HANDLE han;
DWORD threadId;
han = CreateThread(NULL, 0, mb, NULL, 0, &threadId);
han = CreateThread(NULL, 0, mb, NULL, 0, &threadId);
han = CreateThread(NULL, 0, mb, NULL, 0, &threadId);
}
BOOL APIENTRY DllMain() {
create();
return 1;
}
[MS.Docs]: DllMain entry point (emphasis is mine) states:
Calling functions that require DLLs other than Kernel32.dll may result in problems that are difficult to diagnose. For example, calling User, Shell, and COM functions can cause access violation errors, because some functions load other system components. Conversely, calling functions such as these during termination can cause access violation errors because the corresponding component may already have been unloaded or uninitialized.
[MS.Docs]: MessageBox function resides in User32.dll, so it's Undefined Behavior (meaning that in different scenarios, it might work, it might work faulty, or it might crash).
Also, as #RbMm noticed, WaitForSingleObject doesn't belong there. I'm not sure about CreateThread either (but I couldn't find any official doc to confirm / infirm it).
Just out of curiosity, could you add a printf("main called.\n"); in main, to see how many times it is called?
because in general case DLL can be unloaded, need add reference to DLL - for it will be not unloaded until thread, which use it code executed. this can be done by call GetModuleHandleEx - increments the module's reference count unless GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT is specified. when thread exit - we dereference DLL code by call FreeLibraryAndExitThread. wait for all threads exit in most case not need. so code, inside dll can be next
ULONG WINAPI DemoThread(void*)
{
MessageBoxW(0, L"text", L"caption", MB_OK);
// dereference dlll and exit thread
FreeLibraryAndExitThread((HMODULE)&__ImageBase, 0);
}
void someFnInDll()
{
HMODULE hmod;
// add reference to dll, because thread will be use it
if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (PCWSTR)&__ImageBase, &hmod))
{
if (HANDLE hThread = CreateThread(0, 0, DemoThread, 0, 0, 0))
{
CloseHandle(hThread);
}
else
{
// dereference dll if thread create fail
FreeLibrary(hmod);
}
}
}
wait inside dll entry point is wrong, because we hold here process wide critical section. if we wait for thread exit - this wait always deadlock - thread before exit (and start) try enter this critical section, but can not because we wait for him here. so we hold critical section and wait for thread(s), but threads(s) wait when we exit from this critical section. deadlock
I'm writing a C program.
For thread I use the WINAPI library.
But sometimes the CreateThread function don't launch the function associate.
I used the WaitForSingleObject function with INFINITE param to let my thread start but he never start
The GetLastError functions return always 0,so I don't know where is my mistake
The merge function is call when GTK button is press.
Below you will find my code
void merge(GtkWidget *wiget, gpointer data){
HANDLE thread;
FtpLogin *login = (FtpLogin *) data;
thread = CreateThread(NULL, 0, mergeThread, login, 0, NULL);
printf("%ld", GetLastError());
WaitForSingleObject(thread, INFINITE);
if(thread == NULL)
puts("error");
}
DWORD WINAPI mergeThread( LPVOID lpParam )
{
puts("Thread start");
return 0;
}
Thanks for your help
The C run-time library needs some per-thread initialization. CreateThread(), which knows nothing about the C RTL, doesn't perform that.
Instead of CreateThread(), use _beginthreadex(). It's declared in <process.h>.
According to this page, GTK is not thread safe. Anything that interacts with the GUI inside your mergeThread function can have unexpected results.
Please refer to the link I provided for more information about multithreaded GTK applications to see how to use GDK instead.
I'm trying to inject a thread to another process, which let the process load an external dll.
Here's the code I found on the internet, and it works.
HANDLE hThread = CreateRemoteThread (hProcess, NULL, 0,
(LPTHREAD_START_ROUTINE) GetProcAddress(
GetModuleHandle(L"kernel32"), "LoadLibraryA"),
lpMemory, 0, NULL);
if (hThread == INVALID_HANDLE_VALUE)
{
return false;
}
But from my understandings, the address returned by GetProcAddress lives in the memory space of the current process, not the targeted one.
So why does it work?
Tested on Windows 7
I have a thread like this:
DWORD WINAPI message_loop_thread(LPVOID dummy) {
MSG message;
while (GetMessage(&message, NULL, 0, 0)) {
TranslateMessage(&message);
DispatchMessage(&message);
}
}
And i start it with CreateThread:
DWORD thread_id;
CreateThread(0, 0, message_loop_thread, 0, 0, &thread_id);
This seems to work, but how can i correctly close this thread? Normally the thread is waiting for GetMessage so the thread is blocked i think.
Is there a good way to do this? I tried TerminateThread, but this hangs, and i think it's not a good solution to stop the thread.
Has someone an idea?
best regards
Benj Meier
The proper way is to post WM_QUIT to thread_id. You use PostThreadMessage() for this. In response, GetMessage returns 0, the while loop exits, and the function exits (incorrectly, you're missing a return statement). When the toplevel function of a thread exits, the thread ends.
I a have a C program which calls to threads.
iret1 = pthread_create( &thread1, NULL, readdata, NULL);
iret2 = pthread_create( &thread2, NULL, timer_func, NULL);
pthread_join(thread2, NULL);
Thread 2 returns after performing some function, after which I want to stop the execution of thread 1. How should I do this?
You can stop the thread using pthread_cancel:
pthread_cancel(thread1);
And in readdata:
/* call this when you are not ready to cancel the thread */
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
...
/* call this when you are ready to cancel the thread */
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
See the pthread_cancel man page for more information - there's an example included.
If you don't want to use pthread_cancel, you can use a global flag that is set by the main thread and read by thread 1. Also, you can use any of the IPC methods, like establishing a pipe between the threads.
You should signal to the thread that you wish it to stop work, and then wait for it to do so. For example, you could set a boolean flag that the thread tests regularly. If that flag indicates that work has been cancelled, then the thread should return from the thread function.
Don't attempt to forcibly terminate the thread from the outside because this will leave synchronisation objects in indeterminate state, lead to deadlocks etc.
Thread1 must have a flag which it verifies from time to time to see if it should abort itself.
There are ways to abort a thread from outside, but this is very dangerous. Don't.
Something like:
thread1stop=TRUE; //Thread 1 has access to this boolean value
pthread_join(thread1, NULL);
tkill(tid, SIGTERM) is the call you are looking for I do believe.
You can stop thread1 by calling pthread_cancel(thread1).
pthread_cancel() function sends a cancellation request to the thread.
After sending the request to cancel the thread you should check the return code to confirm that the thread was actually cancelled or not.
Here is a simple example:
rc = pthread_cancel(iret2);
if(rc) printf("failed to cancel the thread\n");
For further reference:
http://cursuri.cs.pub.ro/~apc/2003/resources/pthreads/uguide/users-39.htm
Other sources which might be useful to you.
http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_create.3.html
http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_cancel.3.html