GetCurrentThreadId returns different threadId - c++

I call the mentioned windows API. But it returns a different thread id than the id returned by _beginthreadex. My code is following,
ThreadTest *_threadTest = new ThreadTest();
Thread *_thread = new Thread(StartRoutineForThread,_threadTest);
Constructor for Thread class is,
ThreadWin::ThreadWin(void * (*_startRoutine)(void *), void * _argument, bool _isJoinable)
{
unsigned int _threadAddress;
unsigned int threadID = _beginthreadex(
NULL,
0,
(unsigned int (__stdcall *)(void *))_startRoutine,
_argument,
0,
&_threadAddress
);
}
StartRoutineForThread function which is the start routine for thread is following,
void* StartRoutineForThread(void* _argument)
{
ThreadTest *_threadTest = (ThreadTest*)_argument;
_threadTest->Run();
return NULL;
}
void ThreadTest::Run()
{
this->threadID = ::GetCurrentThreadId();
}
Now in the constructor of class Thread the value of the variable threadID differs from the value of class ThreadTest's variablethreadID that I get from the Run function. But the Run function was called from the function that I specified when I have created the thread. So the Run function is running under the same thread that I have created. But then why GetCurrentThreadId() returns different value than what was returned by _beginthreadex ?

Well, _beginthreadex doesn't return thread id. Thread id is stored in _threadAddress, the last parameter of _beginthreadex. Its return value is thread handle (like CreateThread), not id.

According to MSDN, _beginthreadex returns thread handle, and it is not the same as thread ID.

Related

How address of a function will pass to the std::thread

I was debugging a multithreaded application that is using std::thread to run a function. I reach to the following code when debugging.
extern "C" uintptr_t __cdecl _beginthreadex(
void* const security_descriptor,
unsigned int const stack_size,
_beginthreadex_proc_type const procedure,
void* const context,
unsigned int const creation_flags,
unsigned int* const thread_id_result
)
{
_VALIDATE_RETURN(procedure != nullptr, EINVAL, 0);
unique_thread_parameter parameter(create_thread_parameter(procedure, context));
if (!parameter)
{
return 0;
}
DWORD thread_id;
HANDLE const thread_handle = CreateThread(
reinterpret_cast<LPSECURITY_ATTRIBUTES>(security_descriptor),
stack_size,
thread_start<_beginthreadex_proc_type, true>,
parameter.get(),
creation_flags,
&thread_id);
if (!thread_handle)
{
__acrt_errno_map_os_error(GetLastError());
return 0;
}
if (thread_id_result)
{
*thread_id_result = thread_id;
}
// If we successfully created the thread, the thread now owns its parameter:
parameter.detach();
return reinterpret_cast<uintptr_t>(thread_handle);
}
But I couldn't understand how address of the function passed to the CreateThread API. Why is it using thread_start<_beginthreadex_proc_type, true>, and how the address of a function will calculate by this statement in order to run by threads?
The code shown (_beginthreadex function) is part of VC++ CRT (can be found in, e.g.
C:\Program Files (x86)\Windows Kits\10\Source\10.0.17763.0\ucrt\startup\thread.cpp).
An instance of unique_thread_parameter is a structure that holds the thread procedure pointer, the context argument, and thread and module HANDLEs:
// corecrt_internal.h
typedef struct __acrt_thread_parameter
{
// The thread procedure and context argument
void* _procedure;
void* _context;
// The handle for the newly created thread. This is initialized only from
// _beginthread (not _beginthreadex). When a thread created via _beginthread
// exits, it frees this handle.
HANDLE _thread_handle;
// The handle for the module in which the user's thread procedure is defined.
// This may be null if the handle could not be obtained. This handle enables
// us to bump the reference count of the user's module, to ensure that the
// module will not be unloaded while the thread is executing. When the thread
// exits, it frees this handle.
HMODULE _module_handle;
// This flag is true if RoInitialized was called on the thread to initialize
// it into the MTA.
bool _initialized_apartment;
} __acrt_thread_parameter;
// thread.cpp
using unique_thread_parameter = __crt_unique_heap_ptr<
__acrt_thread_parameter,
thread_parameter_free_policy>;
create_thread_parameter creates such an instance:
static __acrt_thread_parameter* __cdecl create_thread_parameter(
void* const procedure,
void* const context
) throw()
{
unique_thread_parameter parameter(_calloc_crt_t(__acrt_thread_parameter, 1).detach());
if (!parameter)
{
return nullptr;
}
parameter.get()->_procedure = procedure;
parameter.get()->_context = context;
// Attempt to bump the reference count of the module in which the user's
// thread procedure is defined, to ensure that the module will stay loaded
// as long as the thread is executing. We will release this HMDOULE when
// the thread procedure returns or _endthreadex is called.
GetModuleHandleExW(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
reinterpret_cast<LPCWSTR>(procedure),
&parameter.get()->_module_handle);
return parameter.detach();
}
thread_start is a template function that invokes the thread procedure:
template <typename ThreadProcedure>
static unsigned long WINAPI thread_start(void* const parameter) throw()
{
if (!parameter)
{
ExitThread(GetLastError());
}
__acrt_thread_parameter* const context = static_cast<__acrt_thread_parameter*>(parameter);
__acrt_getptd()->_beginthread_context = context;
if (__acrt_get_begin_thread_init_policy() == begin_thread_init_policy_ro_initialize)
{
context->_initialized_apartment = __acrt_RoInitialize(RO_INIT_MULTITHREADED) == S_OK;
}
__try
{
ThreadProcedure const procedure = reinterpret_cast<ThreadProcedure>(context->_procedure);
_endthreadex(invoke_thread_procedure(procedure, context->_context));
}
__except (_seh_filter_exe(GetExceptionCode(), GetExceptionInformation()))
{
// Execution should never reach here:
_exit(GetExceptionCode());
}
// This return statement will never be reached. All execution paths result
// in the thread or process exiting.
return 0;
}
It essentially calls invoke_thread_procedure, which just invokes procedure, passing in context:
static __forceinline unsigned int invoke_thread_procedure(
_beginthreadex_proc_type const procedure,
void* const context
) throw()
{
return procedure(context);
}
The code around the calls does some bookkeeping to keep the CRT consistent, for example it
automatically cleans up the thread upon exit (_endthreadex).

passing one function to different threads

I have to create an application where I'll have to make multiple threads. SoI thought to try making one function and passing it to different threads. Initially I've created two threads and have declared one function to be passed to both of them. All I am trying to do is to pass different integers to those threads and display it in the thread function,here is my code:
DWORD WINAPI Name(LPVOID lpParam)
{
int *Ptr=(int*)lpParam;
for(int j=0;j<2;j++)
{
cout<<"Thread"<<endl;
cout<<*Ptr<<endl;
}
return 0;
}
int main()
{
int a=10,b=15,c=25;
HANDLE thread1,thread2;
DWORD threadID,threadID2;
thread2= CreateThread(NULL,0,Name,LPVOID(a),0,&threadID2);
thread1= CreateThread(NULL,0,Name,LPVOID(b),0,&threadID);
for(int i=0;i<5;i++)
{
cout<<"Main Thread"<<endl;
}
if(thread1==NULL)
{
cout<<"Couldn't Create Thread:("<<endl;
exit(0);
}
if(thread2==NULL)
{
cout<<"Couldn't Create Thread:("<<endl;
exit(0);
}
return 0;
}
but this code is not running properly,i.e compliles fine,starts fine but afterwards gives a debugging error.
Could someone let let me know of my mistake and how I could correct it coz being able to utilize one function for multiple threads will be really helpful for me.
Wait for your child threads to return. Do this:
int main()
{
int a=10,b=15,c=25;
HANDLE thread[2];
DWORD threadID,threadID2;
thread[1]= CreateThread(NULL,0,Name,LPVOID(a),0,&threadID2);
thread[0]= CreateThread(NULL,0,Name,LPVOID(b),0,&threadID);
for(int i=0;i<5;i++)
{
cout<<"Main Thread"<<endl;
}
if(thread[0]==NULL)
{
cout<<"Couldn't Create Thread:("<<endl;
exit(0);
}
if(thread[1]==NULL)
{
cout<<"Couldn't Create Thread:("<<endl;
CloseHandle(thread[0]);
exit(0);
}
WaitForMultipleObjects(2, thread, TRUE, INFINITE);
CloseHandle(thread[0]);
CloseHandle(thread[1]);
return 0;
}
The handle of a thread is signaled when the thread is terminated (refer CreateThread).
You are passing the address of a local variable in the function into your thread. By the time the thread gets around to running your function has probably exited main already. So the thread will try to access a variable that no longer exists on the stack so will be reading some random value which when you try to dereference it as a pointer will likely crash.
You main needs to wait. For a simple test just put in a Sleep(10000) or something before it exits. Obviously that's no use for a real program.
To summarize the comments: There are two ways you can pass data. Either directly inside the void pointer, because "void pointer" is an integral type and thus can represent integers (but it doesn't necessarily have the same width as int), or indirectly by passing an actual address of the thing you care about.
Method 1 (pass the value):
DWORD WINAPI Name(LPVOID lpParam)
{
intptr_t n = reinterpret_cast<intptr_t>(lpParam);
// ...
}
int main()
{
intptr_t a = 10;
thread1 = CreateThread(NULL, 0, Name, reinterpret_cast<void *>(a), 0, &threadID);
// ... ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
For this method, we use the integral type intptr_t, which has the same width as void *. We use reinterpret-casts to store and retrieve arbitrary integral values.
Method 2 (pass a pointer):
DWORD WINAPI Name(LPVOID lpParam)
{
T * p = static_cast<T *>(lpParam);
// ... use *p ...
}
int main()
{
T thing_I_care_about;
thread1 = CreateThread(NULL, 0, Name, &thing_I_care_about, 0, &threadID);
// ... ^^^^^^^^^^^^^^^^^^^
}
This is the more general method, but requires that thing_I_care_about remain alive, and it becomes a brittle shared state, so lifetime management and synchronisation become issues. Note that any object pointer is implicitly convertible to void *, so there's no need for the cast at the call site.
Finally, as others have commented, don't forget to join or detach your threads.

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

Define thread in C++

How do I start a thread using _beginthreadex(), making it execute void myFunction(wchar_t *param);? I try to use this:
_beginthread(NULL, 0, myFunction, L"someParam", 0, &ThreadID);
but there is compilation error:
error C2664: 'beginthreadex' : cannot convert parameter 3 from 'void (_cdecl *)(wchar_t *)' to 'unsigned int (__stdcall *)(void *)'.
How I can resolve this error? I seem able to do _beginthread((void(*)(void*))myFunction, 0 , (void *)L"someParam");. But for _beginthreadex() these casts don't seem to work. What do
I need to do?
This code doesn't output anything. What's wrong?
unsigned int __stdcall myFunction( void *someParam )
{
printf("Hello world!");
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
_beginthreadex(NULL, 0, myFunction, L"param", 0, NULL);
return 0;
}
_beginthreadex requires a function that uses the __stdcall calling convention, not the __cdecl calling convention, which is the default. To fix it, declare your thread procedure with the __stdcall calling convention:
unsigned int __stdcall myFunction(void *arg)
{
...
}
Do NOT cast the function pointer you're passing into _beginthread or _beginthreadex: a function pointer cast is a bug waiting to happen.
Function prototype requirements for each Microsoft CRT thread launch functions are:
_beginthread: void __cdecl procname(void * arg);
_beginthreadex: unsigned int __stdcall procname(void *arg);
You should also be aware of the differences between the two.
_beginthread: allocates a new thread and invokes the thread procedure passed as the argument. Using this API the thread-creation parameters are somewhat limited. The return value of this function is a uintptr_t, but is actually a Windows thread handle of type HANDLE. It must be cast to a HANDLE variable to be used in such functions as WaitForSingleObject, etc. When the thread procedure finishes through normal function-exit the thread handle is automatically closed for you by the runtime. This is important. Although this function returns a thread handle just like _beginthreadex, it is conceivable for the thread to start and finish before you can do anything with the handle (such as a wait, suspend, etc.). Once the thread procedure finishes the RT will close the handle, and therefore your local variable holding the initial returned handle is now invalid.
_beginthreadex: allocates a new thread and invokes the thread procedure passed as the argument. This version allows significantly more control over how the thread is created, including the stack size, initial suspended state, etc. The return value of this function is a uintptr_t, but is actually a Windows thread handle of type HANDLE. It must be cast to a HANDLE variable to be used in such functions as WaitForSingleObject, etc. When the thread procedure finishes through normal function-exit the thread handle is NOT automatically closed for you by the runtime. You are responsible for closing the thread handle returned by this function, and should do so as soon as it is no longer needed.
Which to use: Use _beginthread if you have no need for the thread handle to be used in Wait functions and such, and have no special thread-creation needs (like creating a thread with an initially-suspended state). Use _beginthreadex when you need a wait'able thread handle, finer control over the creation parameters, etc.
EDIT: Sample for the OP
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <process.h>
unsigned int __stdcall MyThread(void *p)
{
_tprintf(_T("%s\n"), p);
_tprintf(_T("Thread finishing!\n"));
return 0;
}
int _tmain(int argc, TCHAR *argv[])
{
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, MyThread, _T("Hello, World!"), 0, NULL);
if (hThread != INVALID_HANDLE_VALUE)
{
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
_tprintf(_T("Thread finished!\n"));
}
return 0;
}
As in the other answer above, don't forget to wait for your thread to finish before _tmain exits, or you likely will see no output.

C++ Class: Object that creates Thread + pointer to the function = Access violation

I am very surprised by the strange exception, that I got.
class Threads {
public:
Threads() {}
~Threads() {}
void StartThread(int (*p)()); //pointer to a function
private:
HANDLE hThread;
DWORD dwThreadID;
};
Method StartThread should receive pointer to my function (that will be run in another thread).
This function is simple. (as you can see it is situated outside the class Threads):
int MyThread()
{
return 0;
}
And this is method of creating thread:
inline void Threads::StartThread(int (*p)())
{
hThread = CreateThread(NULL,
0,
(LPTHREAD_START_ROUTINE)(*p)(),
NULL,
0,
&dwThreadID);
if (hThread == NULL)
{
return;
}
}
Here compiler get error: cannot convert parameter 3 from 'int' to 'LPTHREAD_START_ROUTINE'. That why I did the casting.
In main function I create object of type Threads and I try to call method StartThread. As parameter I send pointer to the function MyThread.
Threads *thread1;
thread1 = new Threads();
thread1->StartThread(MyThread);
I thought MyThread must start in another thread. But the function MyTread always runs in Main Thread!!! And only after MyThread ends, another thread starts and then I get this exception:
Unhandled exception at 0x00000000 in ThreadClass.exe: 0xC0000005: Access violation.
I need clever advice!
The call convention is wrong:
LPTHREAD_START_ROUTINE is a __stdcall method not a __cdecl method, see the documentation here: http://msdn.microsoft.com/en-us/library/aa964928.aspx.
It looks like you are actually calling the function on this line...
(LPTHREAD_START_ROUTINE)(*p)()
...and it returns an int that you're casting. That just can't work. How about:
(LPTHREAD_START_ROUTINE)p
...instead?