new Thread making only first instruction and never resumes - c++

Here is my problem:
I'm creating threads
HANDLE Threads[THREAD_NUM]
Launch the thread
void LaunchThread (int i) {
*some checks if the handle is not null etc*;
DWORD threadId;
threads[i] = CreateThread (
NULL,
0,
(LPTHREAD_START_ROUTINE)*StaticMethodInvokingTheThreadFunc,
*StructPassingToThatMethod ( basically have a pointer and thread number)*,
0,
&threadId);
*DebugMessage "thread created"*;
*DebugMessage "with id = (threadId)"*;
}
Static method invokes function
void DoSmth () {
*DebugMessage "thread func started"*;
...;
*then code with another messages all the way*;
}
Waiting function is simple
void WaitThread (i){
*DebugMessage "wait for thread to finish"*;
WaitForSingleObject (Threads[i], INFINITE);
}
And in main function the sequence:
LaunchThread (i);
WaitThread (i);
Program never returns the WaitThread () function, and(!) the list of messages looks like
"thread created"
"thread func started" (and nothing done after that message in DoSmth () func)
"with id = .."
"wait for thread to finish"
This happens even with 1 thread...
For a couple of threads i simply have
for ( int t = 0; t < THREAD_NUM; t++)
LaunchThread (t);
and the same loop for waiting threads
Why is this happening?
I tried to ResumeThread (), to close handle to thread and relaunch it, but nothing helped.

It could be that function StaticMethodInvokingTheThreadFunc does not really have a signature of LPTHREAD_START_ROUTINE, but this is masked by the fact that the function pointer is forcefully cast to it. Remove the cast. If compiler starts to complain then adapt the signature of your function.
It could be that calling CreateThread is wrong in your case. It is wrong in 99% cases, and you should really call CRT library function _beginthreadex. This function internally calls CreateThread, but it also does some initialization stuff. Replace CreateThread with _beginthreadex.
It could be that the execution is hang in StaticMethodInvokingTheThreadFunc, after the text "thread func started" is printed. Revise the code in the function, or place a breakpoint on last function's line and debug the project to see if breakpoint will be hit.

Related

WINAPI CreateThread not always running thread

I am trying to create and execute a thread using Windows CreateThread API. am seeing that running the program gives non-deterministic behavior. I am seeing from the output of the program that sometimes the thread method "my" gets executed and sometimes not. What might be the reason for this? The program is very simple as shown below. Also what should dwThreadID be initialized with. Should it be 0 or any integer value?
PS:Compiling in Visual Studio.
#include "stdafx.h"
#include <iostream>
#include <windows.h>
using namespace std;
// DWORD WINAPI
DWORD WINAPI my (LPVOID lpParam ) {
for (int i = 0; i < 5;i++){
cout << "I am ";
}
return 0;
}
int main()
{
DWORD dwThreadID = 0;
DWORD dwThrdParam = 0;
HANDLE h = NULL;
h = CreateThread(
NULL, // default security
0, // default stack size
my, // name of the thread function
0, // no thread parameters
0, // default startup flags
&dwThreadID);
if (h == NULL){
cout <<"It is null";
}
cout << " BBBB" << endl ;
CloseHandle(h);
cout << "BBBB ";
return 0;
}
I am seeing from the output of the program that sometimes the thread
method "my" gets executed and sometimes not. What might be the reason
for this?
Probably your main thread exits before your second thread is even executed. Place breakpoint after call to CreateThread.
Or even more cleaner wait, just wait for second thread using WaitForSingleObject.
This effectively make your main thread waiting until "my" thread is done.
If CreateThread fails for some reason, you can call GetLastError right after CreateThread, it will give you ultimate answer.
Also what should dwThreadID be initialized with.
Quick look into MSDN yields following:
A pointer to a variable that receives the thread identifier.
It is indeterminate whether or not your thread executes. The main thread creates it and then terminates the program. The following may happen:
The thread may execute before the main thread terminates.
The program may terminate before the thread executes.
The thread may partially execute and be terminated when the program terminates.
You would need to add synchronization in order to be sure that the thread reaches completion. Pass the thread handle to WaitForSingleObject.
Your program does not check for errors. CreateThread returns NULL when it fails. If that happens, and only if that happens, call GetLastError for information as to why the function failed. If you add a call to WaitForSingleObject then you should check its return value for errors as described by the documentation.
What should dwThreadID be initialized with?
It does not need to be initialized because CreateThread guarantees it will be assigned if CreateThread succeeds.
Firstly do not use CreateThread it is intended for library providers. Use beginthreadex or std::thread
The likely behavior, is that the thread always runs, but it's output is being overwritten. This is because there is no synchronisation.
Check the return code and GetLastError
The value of dwThreadid does not matter

Windows: WaitForSingleObject crashes when thread returns 0

I am having a strange behavior: WaitForSingleObject seems to crash when I return 0 from my thread, but if I call "ExitThread(0)" then it does not.
void waitForThread(DWORD &threadId)
{
HANDLE hThread = OpenThread(SYNCHRONIZE,
FALSE,
threadId);
if (hThread == NULL) return;
WaitForSingleObject(hThread, INFINITE); // Crashes here (not even returning)
CloseHandle(hThread);
}
According to the documentation:
ExitThread is the preferred method of exiting a thread in C code. However, in C++ code, the thread is exited before any destructors can be called or any other automatic cleanup can be performed. Therefore, in C++ code, you should return from your thread function.
This does not make sense to me. I would think that "return 0" in my function with the signature:
DWORD WINAPI foo(LPVOID arg);
would be fine. For completeness, the thread is created using CreateThread, as such:
DWORD threadId;
HANDLE pth = CreateThread(NULL, // Default security attributes
0, // Default stack size
foo, // Thread name
arg, // Argument to thread
0, // Default creation flag
&threadId); // Returns thread ID
Does anyone know why the return statement would crash "WaitForSingleObject" please? I have put print statement before and after WaitForSingleObject, and one when the thread exists, and the behavior I see is: "Before WaitForSingleObject", "Thread finishes", Crash. Does anyone understand this behavior please?

Thread does nothing after successful pthread_create

In my project I want to create thread which do nothing but append some string to textfile to test if it works. I'm using IDE Eclipse Juno on Ubuntu 12.04. Part of my code is:
pthread_t processThread;
threadData * thData = new threadData;
int t = pthread_create(&processThread, NULL,
BufferedData::processData, (void *)thData);
where threadData is struct with parameters for thread. Thread start member function of class BufferedData so processData method is static. Its declaration is:
static void * processData(void * arg);
After this part of code I check t value - the returning value of pthread_create. Everytime it is equals to 0 so I suppose that start of thread was succesful. But still it does nothing - it doesn't append string to file. It doesn't matter what function processData do: append string to file, throw exception, write to cout or something else. It does nothing everytime.
I'm not experienced C++ programmer so I don't know what to check, edit or do to solve the problem. IDE doesn't give me any response that something is wrong, it faces as everything is ok.
Thanks for your answers.
EDIT:
the code of processData function:
void * BufferedData::processData(void * arg) {
HelperFunctions h;
h.appendToFile("log", "test");
return 0;
}
appendToFile method write string "test" to file "log". This is tested in other projects and it works.
Now your thread will be finished in a time (not infinite), so this can help you :
int pthread_join(pthread_t thread, void **status);
In bellow code, when your thread created then pthread_join function waiting for a return from your thread. in this state use of pthread_exit() instead of return keyword.
Try this pthread_join() :
void *ret;
pthread_t processThread;
threadData * thData = new threadData;
int t = pthread_create(&processThread, NULL,
BufferedData::processData, (void *)thData);
if (pthread_join(processThread, &ret) != 0) {
perror("pthread_create() error");
exit(3);
}
delete ret; // dont forget to delete ret (avoiding of memory leak)
And use of pthread_exit() :
void * BufferedData::processData(void * arg) {
int *r = new int(10);
HelperFunctions h;
h.appendToFile("log", "test");
pthread_exit(static_cast<void*>(a));
}
General description
Allows the calling thread to wait for the ending of the target thread.
pthread_t is the data type used to uniquely identify a thread. It is returned by pthread_create() and used by the application in function calls that require a thread identifier.
status contains a pointer to the status argument passed by the ending thread as part of pthread_exit(). If the ending thread terminated with a return, status contains a pointer to the return value. If the thread was canceled, status can be set to -1.
Returned value
If successful, pthread_join() returns 0.
If unsuccessful, pthread_join() returns -1 and sets errno to one of the following values :
Error Code :
Description :
EDEADLK
A deadlock has been detected. This can occur if the target is directly or indirectly joined to the current thread.
EINVAL
The value specified by thread is not valid.
ESRCH
The value specified by thread does not refer to an undetached thread.
Notes:
When pthread_join() returns successfully, the target thread has been detached.
Multiple threads cannot use pthread_join() to wait for the same target thread to end. If a thread issues pthread_join() for a target thread after another thread has successfully issued pthread_join() for the same target thread, the second pthread_join() will be unsuccessful.
If the thread calling pthread_join() is canceled, the target thread is not detached

c++ winapi threads

These days I'm trying to learn more things about threads in windows. I thought about making this practical application:
Let's say there are several threads started when a button "Start" is pressed. Assume these threads are intensive (they keep running / have always something to work on).
This app would also have a "Stop" button. When this button is pressed all the threads should close in a nice way: free resources and abandon work and return the state they were before the "Start" button was pressed.
Another request of the app is that the functions runned by the threads shouldn't contain any instruction checking if the "Stop" button was pressed. The function running in the thread shouldn't care about the stop button.
Language: C++
OS: Windows
Problems:
WrapperFunc(function, param)
{
// what to write here ?
// if i write this:
function(param);
// i cannot stop the function from executing
}
How should I construct the wrapper function so that I can stop the thread properly?
( without using TerminateThread or some other functions )
What if the programmer allocates some memory dynamically? How can I free it before closing
the thread?( note that when I press "Stop button" the thread is still processing data)
I though about overloading the new operator or just imposing the usage of a predefined
function to be used when allocating memory dynamically. This, however, means
that the programmer who uses this api is constrained and it's not what I want.
Thank you
Edit: Skeleton to describe the functionality I'd like to achieve.
struct wrapper_data
{
void* (*function)(LPVOID);
LPVOID *params;
};
/*
this function should make sure that the threads stop properly
( free memory allocated dynamically etc )
*/
void* WrapperFunc(LPVOID *arg)
{
wrapper_data *data = (wrapper_data*) arg;
// what to write here ?
// if i write this:
data->function(data->params);
// i cannot stop the function from executing
delete data;
}
// will have exactly the same arguments as CreateThread
MyCreateThread(..., function, params, ...)
{
// this should create a thread that runs the wrapper function
wrapper_data *data = new wrapper_data;
data->function = function;
data->params = params;
CreateThread(..., WrapperFunc, (LPVOID) wrapper_data, ...);
}
thread_function(LPVOID *data)
{
while(1)
{
//do stuff
}
}
// as you can see I want it to be completely invisible
// to the programmer who uses this
MyCreateThread(..., thread_function, (LPVOID) params,...);
One solution is to have some kind of signal that tells the threads to stop working. Often this can be a global boolean variable that is normally false but when set to true it tells the threads to stop. As for the cleaning up, do it when the threads main loop is done before returning from the thread.
I.e. something like this:
volatile bool gStopThreads = false; // Defaults to false, threads should not stop
void thread_function()
{
while (!gStopThreads)
{
// Do some stuff
}
// All processing done, clean up after my self here
}
As for the cleaning up bit, if you keep the data inside a struct or a class, you can forcibly kill them from outside the threads and just either delete the instances if you allocated them dynamically or let the system handle it if created e.g. on the stack or as global objects. Of course, all data your thread allocates (including files, sockets etc.) must be placed in this structure or class.
A way of keeping the stopping functionality in the wrapper, is to have the actual main loop in the wrapper, together with the check for the stop-signal. Then in the main loop just call a doStuff-like function that does the actual processing. However, if it contains operations that might take time, you end up with the first problem again.
See my answer to this similar question:
How do I guarantee fast shutdown of my win32 app?
Basically, you can use QueueUserAPC to queue a proc which throws an exception. The exception should bubble all the way up to a 'catch' in your thread proc.
As long as any libraries you're using are reasonably exception-aware and use RAII, this works remarkably well. I haven't successfully got this working with boost::threads however, as it's doesn't put suspended threads into an alertable wait state, so QueueUserAPC can't wake them.
If you don't want the "programmer" of the function that the thread will execute deal with the "stop" event, make the thread execute a function of "you" that deals with the "stop" event and when that event isn't signaled executes the "programmer" function...
In other words the "while(!event)" will be in a function that calls the "job" function.
Code Sample.
typedef void (*JobFunction)(LPVOID params); // The prototype of the function to execute inside the thread
struct structFunctionParams
{
int iCounter;
structFunctionParams()
{
iCounter = 0;
}
};
struct structJobParams
{
bool bStop;
JobFunction pFunction;
LPVOID pFunctionParams;
structJobParams()
{
bStop = false;
pFunction = NULL;
pFunctionParams = NULL;
}
};
DWORD WINAPI ThreadProcessJob(IN LPVOID pParams)
{
structJobParams* pJobParams = (structJobParams*)pParams;
while(!pJobParams->bStop)
{
// Execute the "programmer" function
pJobParams->pFunction(pJobParams->pFunctionParams);
}
return 0;
}
void ThreadFunction(LPVOID pParams)
{
// Do Something....
((structFunctionParams*)pParams)->iCounter ++;
}
int _tmain(int argc, _TCHAR* argv[])
{
structFunctionParams stFunctionParams;
structJobParams stJobParams;
stJobParams.pFunction = &ThreadFunction;
stJobParams.pFunctionParams = &stFunctionParams;
DWORD dwIdThread = 0;
HANDLE hThread = CreateThread(
NULL,
0,
ThreadProcessJob,
(LPVOID) &stJobParams, 0, &dwIdThread);
if(hThread)
{
// Give it 5 seconds to work
Sleep(5000);
stJobParams.bStop = true; // Signal to Stop
WaitForSingleObject(hThread, INFINITE); // Wait to finish
CloseHandle(hThread);
}
}

WaitForSingleObject problem

Read the problem carefully first.
There is a worker thread which gets spawned from a CreateInstance of CTest class. Here is the prototype of the class. hThread is the handle to thread and hEventShutdown is the event used to shutdown thread when program exits. WaitForShutdown is the public function which is used to signal hEventShutdown and wait on handle to thread till thread exits gracefully. WaitForShutdown is invoked from Exit of Application.
//pseudocode
CTest
{
public:
CTest* CreateInstance();
static threadproc(void *pv);
void WaitForShutdown();
public:
HANDLE hThread;
HANDLE hEventShutdown;
}
void CTest::CTest* CreateInstance()
{
// spawn a thread, pass 'this' pointer to thread , use beginthreadex
hThread = beginthreadex ( threadproc, this );
}
unsigned int CTest::threadproc( void *pv)
{
Ctest *ptest = (Ctest*)pv;
do
{
HANDLES hArray[2] = { pv->hEventShutdown, someotherhandle }
dwResult = Waitformultipleobjects( hArrary , 2);
if ( dwResult == WAIT_OBJECT_0)
delete pTest; // since it is allocated dynamically ( This is required due to some known reasons in my code)
if(dwResult == WAIT_OBJECT_0 + 1)
Doprocessing(); //DoProcessing when other thread signal someotherhandle
}while (1)
void CTest::WaitForShutdown()
{
SetEvent ( hEventShutdown);
WaitForSingleObject ( hThread,INFINITE);
}
void CTest::~CTest()
{
Closehandle(hThread)
Closehandle(hEventShutdown);
}
Now if you look at the code carefully, you will find that event is signaled from WaitForShutdown function, thread comes out of WaitForMultipleOjbects and deletes pointer of CTest. It means destructor of CTest is invoked which will obviously close thread handle ( hThread). But WaitForSingleObject from WaitForShutdown is actually waiting on thread handle. So here behavior will be undefined ( I think so, you can correct me if I am wrong). Another problem is destructor of Ctest is invoked when WaitForSingleObject is waiting on its member hThread which is not correct. I can not remove delete pTest from thread since it has to be there due to some reasons.
How will you suggest the solution to the above ?
Couple of Solution which I can think of :
I can keep thread handle in another map but I dont want to do it.
I can copy thread handle to some local variable before WaitForSingleObject in WaitForShutdown and will wait on it. Don;t know is it right ? you tell me.
Or I will use Duplicatehandle API to get reference of existing thread handle before WaitForSingleObject and wait on it. Dont know is it correct. Dont know if will the duplicate handle be alive after CloseHandle on original.
I will keep thread ID, get thread handle from thread ID and keep waiting on thread handle in WaitForShutdown. This looks more elegant but I do not know is there any way to get handle from thread id.
Correct me.
Your feedback appreciated.
The simplest way to handle this would be to simply delete the thread from WaitForShutdown, after WaitForSingleObject returns. This ensures all the handles you need - and more importantly, the object itself - remain alive to the end.
I have run this piece as is. Seems it works, and it doesn't crash.
Strangely that we can call CloseHandle(hthread), before we go out of WaitforSingleObject(hThread,INFINITE).
Of course, "academic" way to join thread is firstly WaitForSingleObject(hThread,INFINITE) than CloseHandle(hThread). So that is my suggestion - do in this way.
I don't have to add anymore.