passing a structure to a thread - c++

I want to know how to pass a structure to a thread. I've written an example application where I declare a structure in main and try to pass it to the thread.
Here's my code:
DWORD WINAPI Name1(LPVOID lparam)
{
data x;
x.name[15]="Sarah";
x.DOB="19/10/2007";
fputs(stdout,name,15);
fputs(stdout,DOB,15);
return 0;
}
int main()
{
struct data
{
char name[15];
char DOB[15];
};
HANDLE thread2;
DWORD threadID2;
thread2= CreateThread(NULL,0,Name1,(LPVOID *)data,0,&threadID2);
if(thread2==NULL)
{
cout<<"Couldn't Create Thread:("<<endl;
exit(0);
}
return 0;
}
Unfortunately, I am not getting the hang of passing a structure to a thread :( I would really appreciate it if somebody helped me out.
I tried to change the datatype of the structure to pass it, but, I guess I don't know how to do it.

You are passing a local variable to the thread startup function. Once the variable goes out of scope it will be destroyed. This means it may not exist when the new thread tries to access it. You should either pass by value for integral types or allocate the object in dynamic storage (the heap).
Once the new thread has the pointer to the object it should probably be responsible for destroying it as well. That all depends on how you want to assign and manager ownership of the object.
struct Foo
{
char name[15];
char DOB[15];
};
void Start()
{
Foo *someObject = new Foo();
CreateThread(NULL, 0, threadFunc, (LPVOID *)someObject, 0, &threadID2);
}
DWORD WINAPI threadFunc(void *v)
{
Foo *someObject = static_cast<Foo*>(v);
delete someObject;
return 0;
}

If you want to pass a struct to a thread, you've to get that struct on the heap and not on the stack and pass its address to the thread.
I also fixed a few mistakes... Like string copy, and so on...
I didn't use any typedef, as it appears you're using C++.
struct data{
char name[15];
char DOB[15];
};
DWORD WINAPI Name1(LPVOID lparam)
{
data *x = (data*)lparam;
strcpy(x->name, "Sarah");
strcpy(x->DOB, "19/10/2007");
fputs(stdout, x->name, 15);
fputs(stdout, x->DOB, 15);
HeapFree(GetProcessHeap(), 0, x);
return 0;
}
int main()
{
HANDLE thread2;
DWORD threadID2;
data * x;
x = HeapAlloc(GetProcessHeap(), 0, sizeof(data));
thread2= CreateThread(NULL, 0, Name1, (LPVOID)x, 0, &threadID2);
if(thread2==NULL)
{
cout << "Couldn't Create Thread:(" << endl;
exit(0);
}
return 0;
}

Related

passing a single integer to a multithread function in C++

I want to call a function with multiple threads, and I only need to pass a single integer to that function (the thread id, so if it is accessible I need no value to pass).
How should I do this?
for example like:
for(int i=0; i < numberOfThread; i++ ){
pthread_create(&threads[i], NULL, multichaper, &td[i]);
}
in which multichaper is my function and threadID is an integer.
Update: I marked the answer from user3286661 as the right answer and that worked for me, if you want a more detailed answer you can check my own solution to this question in answers.
General approach to this is to make the function like this:
void* multichaper(void* arg) {
int tid = *(int*)arg;
...
}
And while calling pthread_create:
pthread_create(&threads[i], NULL, multichaper, &td[i])
where td[i] is an int.
You really should consider moving to C++11 threads:
#include <thread>
#include <iostream>
void show_id(int id) {
std::cout << id << std::endl;
}
int main()
{
std::thread t(show_id, 10);
t.join();
}
If you must use pthreads, though:
#include <iostream>
#include <pthread.h>
void *show_id(void *x_void_ptr)
{
const int id = *static_cast<int *>(x_void_ptr);
std::cout << id << std::endl;
return NULL;
}
int main()
{
pthread_t t;
int id = 10;
if(pthread_create(&t, NULL, show_id, &id)) {
std::cerr << "couldn't create" << std::endl;
return -1;
}
if(pthread_join(t, NULL)) {
std::cerr << "couldn't join" << std::endl;
return -2;
}
}
Note how much better the first version is:
No casts
Fewer explicit checks
No problem with the lifetime of the object you're passing - in the first version, you're passing a pointer to it, and thus must ensure it's "alive" while the thread is using it.
No unintuitive void * returns (with the same lifetime problems).
No. You can't do that. The function you pass to pthread_create must have the signature void *(*start_routine) (void *). That is, a function taking a non-const pointer to void and returning a non-const pointer to void.
The simplest way is something like:
int *arg = new int(threadID);
pthread_create(&threads[i], NULL, multichaper, threadID );
and then multichaper looks like:
void *multichaper(void *arg)
{
int *pint = static_cast<int*>(arg);
int threadID = *pint;
delete pint;
...
return nullptr;
}
Note that I have allocated the int on the heap to avoid having to worry about variable lifetimes. If you can guarantee that the variable threadID in the calling function will outlive the thread, then you can skip that bit.
I strongly recommend you use C+11 and the built-in threading library, or if you can't do that, use boost::threads. They both make this much easier!
As i want to pass numbers from 0 to NumberOfThreads to my function i finally used the code below, by passing an integer inside a struct and locking (lock_mutex) that when trying to retrieve the threadNum:
Calling function in multi threads in a member function of SVAnchor class:
pthread_t threads[this->numberOfThread];
pthread_attr_t attr;
params_t params;
pthread_mutex_init (&params.mutex , NULL);
pthread_cond_init (&params.done, NULL);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(int i=0; i < this->numberOfThread; i++ ){
params.id = i;
params.ptr = this;
rc = pthread_create(&threads[i], NULL, &(SVAnchor::multichaperWrapper), &params);
pthread_cond_wait (&params.done, &params.mutex);
}
pthread_attr_destroy(&attr);
void* status;
for(int i=0; i < this->numberOfThread; i++ )
rc = pthread_join(threads[i], &status);
pthread_mutex_destroy (&params.mutex);
pthread_cond_destroy (&params.done);
with params_t as follows:
struct params {
SVAnchor* ptr;
pthread_mutex_t mutex;
pthread_cond_t done;
int id;
};
typedef struct params params_t;
and then multichaperWrapper is as follows:
void* SVAnchor::multichaperWrapper(void* arg){
return (((params*)arg)->ptr)->multichaper( ((params*)arg));
}
and multichaper is as follows:
void* SVAnchor::multichaper( void *threadarg /*0 <= threadNum < numberofthreads*/ ){
int threadNum;
/* Lock. */
pthread_mutex_lock(&(*(params_t*)(threadarg)).mutex);
/* Work. */
threadNum = (*(params_t*)(threadarg)).id;
/* Unlock and signal completion. */
pthread_mutex_unlock(&(*(params_t*)(threadarg)).mutex);
pthread_cond_signal (&(*(params_t*)(threadarg)).done);
cout<<threadNum<<endl;
...
}
If all you want to do is pass an id to the calling thread you can do so by burying it in the void* parameter, and do so portably. Like,
pthread_create(&threads[i], NULL, multichaper, (void*)threadID );

Can't figure out syntax to call multiple object functions as separate threads

I have an array of objects and want each one to call a member function in a separate thread (so they run concurrently). I'm using _beginthreadex and can get it to work fine for a standard function but can't figure out the syntax to pass the member function to the _beginthreadex call. Here's an example of what I'm doing (the block of code after the second comment does not compile):
#include <Windows.h>
#include <process.h>
#include <stdio.h>
unsigned __stdcall mythread(void* data) {
printf("\nThread %d", GetCurrentThreadId());
return 0;
}
class myClass {
public:
unsigned __stdcall myClass::myThread(void* data);
};
unsigned __stdcall myClass::myThread(void* data) {
printf("\nThread %d", GetCurrentThreadId());
return(0);
}
int main(int argc, char* argv[]) {
int i, numThreads = 5;
// this works
HANDLE *myHandle = new HANDLE[numThreads];
for(i=0;i<numThreads;i++) myHandle[i] = (HANDLE)_beginthreadex(0, 0, &mythread, 0, 0, 0);
WaitForMultipleObjects(numThreads, myHandle, true, INFINITE);
for(i=0;i<numThreads;i++) CloseHandle(myHandle[i]);
getchar();
delete myHandle;
// this does not compile - not sure of syntax to call myObject[i].myThread in _beginthreadex
HANDLE *myHandle2 = new HANDLE[numThreads];
myClass *myObject = new myClass[numThreads];
for(i=0;i<numThreads;i++) myHandle2[i] = (HANDLE)_beginthreadex(0, 0, &myObject[i].myThread, 0, 0, 0);
WaitForMultipleObjects(numThreads, myHandle2, true, INFINITE);
for(i=0;i<numThreads;i++) CloseHandle(myHandle2[i]);
getchar();
delete myObject;
delete myHandle2;
return 0;
}
Thanks in advance for any help!
rgames
You cannot get address of member fuinction using
&myObject[i].myThread
correct way is like this
&myClass::myThread
In C++ functions and member functions have different signature like
/* pointer for this function would have type void(*)(int, float) */
void foo(int, float) { /* ... */ }
class A {
public:
/* pointer for this function would have type void(A::*)(int, float) */
void foo(int, float) { /* ... */ }
};
they are have different type even they both return void and take int and float.
As you can see in msdn the _beginthread function takes function as
unsigned (__stdcall *)( void * )
but you are trying to pass
unsigned (__stdcall myClass::*)( void* )
So to correct your code you can do:
Method 1: you need to write another function, something like
unsigned __stdcall mymemberthread(void* data) {
if (data != NULL) {
myClass* m = (myClass*)data;
m->myThread(m + 1);
}
return 0;
}
And create thread like
(HANDLE)_beginthreadex(0, 0, &mymemberthread, &myObject[i], 0, 0);
Method 2: make function myClass::myThread static
class myClass {
public:
static unsigned __stdcall myThread(void* data);
};
unsigned __stdcall myClass::myThread(void* data) {
printf("\nThread %d", GetCurrentThreadId());
if (data != NULL) {
myClass* m = (myClass*)data;
m->myThread(m + 1);
}
return(0);
}
...
(HANDLE)_beginthreadex(0, 0, &myClass::myThread, &myObject[i], 0, 0);
Method 3: if this is acceptabe use STL and std::thread, this will make you code more generic.

C++ Wait all threads to finish

#include <stdio.h>
#include <process.h>
#include <wtypes.h>
typedef unsigned int (__stdcall * THREAD_FUN_TYPE)(void *);
int ThreadIp(void* param)
{
while(true)
{
printf("I'm runing!\n");
}
return 0;
}
int main()
{
int iThreadNum=100;
HANDLE* phThreads = new HANDLE[iThreadNum];
for (int i=0;i<iThreadNum;++i)
{
phThreads[i]=(HANDLE*)_beginthreadex(NULL, 0, (THREAD_FUN_TYPE)ThreadIp,NULL, NULL, NULL);
}
int nIndex = ::WaitForMultipleObjects(iThreadNum,phThreads,1,INFINITE);
printf("End!\n");
return 0;
}
I want the program will halt at WaitForMultipleObjects until all thread are end(Not until all thread are created successfully).But the program will not halt at WaitForMultipleObjects,while all threads are still running. So I try to use SetEvent,but still the same problem:
int iThreadNum=100;
HANDLE* phThreads = new HANDLE[iThreadNum];
for (int i=0;i<iThreadNum;++i)
{
phThreads[i]=CreateEvent(NULL, FALSE, FALSE,NULL);
ResetEvent(phThreads[i]);
}
int nIndex = ::WaitForMultipleObjects(iThreadNum,phThreads,1,INFINITE);
You should wait on the thread handles, not the unrelated events:
Try something like this:
int iThreadNum=100;
HANDLE* phThreads = new HANDLE[iThreadNum];
for (int i=0;i<iThreadNum;++i)
{
m_iCurThreadNum=i;
phThreads[i] = _beginthreadex(...);
}
int nIndex = ::WaitForMultipleObjects(iThreadNum,phThreads,1,INFINITE);
Does it work if you have fewer threads? The manual says you need to do extra work if you have more than MAXIMUM_WAIT_OBJECTS, specifically
nCount [in] The number of object handles in the array pointed to by
lpHandles. The maximum number of object handles is
MAXIMUM_WAIT_OBJECTS. This parameter cannot be zero.
See here for a discussion.
It might be worth checking what the wait function has returned too.
I would allocate a struct before calling _beginthreadex and pass the pointer to the struct through the threads parameter and have the struct contain a bool which is set by the thread when it's done.
struct ThreadStruct{
bool Done;
char* ParamData;
int ParamDataSize;
};
int ThreadIp(void* param)
{
ThreadStruct* ts = (ThreadStruct*)param;
while(true)
{
printf("I'm runing!\n");
}
ts->Done = true;
return 0;
}
int main()
{
int iThreadNum=100;
HANDLE* phThreads = new HANDLE[iThreadNum];
ThreadStruct* structs = new ThreadStruct[iThreadNum];
for (int i=0;i<iThreadNum;++i)
{
ZeroMemory(structs[i], sizeof(ThreadStruct));
phThreads[i]=(HANDLE*)_beginthreadex(NULL, 0, (THREAD_FUN_TYPE)ThreadIp, structs[i], NULL, NULL);
ResetEvent(phThreads[i]);
}
for(unsigned int i=0; i<iThreadNum;){
if(!structs[i]->Done) i=0;
else i++;
}
printf("End!\n");
return 0;
}

Windows CreateThread within a class function call, pointer reference crash?

Below I have an int main() and two header files, one of which is a class for creating a thread and another which is a class called object that gets created within the windows_thread class. This really simple exercise should output 99 but instead its 1 (for some unknown reason). I also tried using a pointer to an object made by new which crashed when void call() from the function Thread_no_1( ) to the class object is made, maybe because its none existent. I hope someone could remedy this otherwise I'll just use windows threads in int main().
this is the main.
#include "windows_thread.h"
int main()
{
windows_thread* THREAD = new windows_thread();
THREAD->thread();
delete THREAD;
return 0;
}
this is the windows_thread.h
#include <windows.h>
#include <stdio.h>
#include "object.h"
#define BUF_SIZE 255
class windows_thread
{
object OBJECT;
public:
windows_thread():OBJECT(99)
{
//OBJECT = new object(99);
}
~windows_thread()
{
//delete OBJECT;
}
void thread()
{
std::cout<<"void thread: "<<std::endl;
int Data_Of_Thread_1 = 1; // Data of Thread 1
HANDLE Handle_Of_Thread_1 = 0; // variable to hold handle of Thread 1
HANDLE Array_Of_Thread_Handles[1]; // Aray to store thread handles
// Create thread 1.
Handle_Of_Thread_1 = CreateThread( NULL, 0, Wrap_Thread_no_1, &Data_Of_Thread_1, 0, NULL);
if ( Handle_Of_Thread_1 == NULL) ExitProcess(Data_Of_Thread_1);
// Store Thread handles in Array of Thread Handles as per the requirement of WaitForMultipleObjects()
Array_Of_Thread_Handles[0] = Handle_Of_Thread_1;
// Wait until all threads have terminated.
WaitForMultipleObjects( 1, Array_Of_Thread_Handles, TRUE, INFINITE);
printf("Since All threads executed lets close their handles \n");
// Close all thread handles upon completion.
CloseHandle(Handle_Of_Thread_1);
}
void DisplayMessage (HANDLE hScreen, char *ThreadName, int Data, int Count)
{
TCHAR msgBuf[BUF_SIZE];
size_t cchStringSize;
DWORD dwChars;
// Print message using thread-safe functions.
//StringCchPrintf(msgBuf, BUF_SIZE, TEXT("Executing iteration %02d of %s having data = %02d \n"), Count, ThreadName, Data);
//StringCchLength(msgBuf, BUF_SIZE, &cchStringSize);
WriteConsole(hScreen, msgBuf, cchStringSize, &dwChars, NULL);
Sleep(1000);
}
DWORD WINAPI Thread_no_1( )
{
std::cout<<"Thread_no_1: "<<std::endl;
OBJECT.call();
//OBJECT->call();
return 0;
}
static DWORD WINAPI Wrap_Thread_no_1( LPVOID lpParam )
{
std::cout<<"Wrap_Thread_no_1: "<<std::endl;
windows_thread *self = reinterpret_cast<windows_thread*>(lpParam);
self->Thread_no_1();
return 0;
}
};
next is the object.h
#ifndef OBJECT_H
#define OBJECT_H
#include <iostream>
class object
{
private:
int value;
public:
object(int value)
{
std::cout<<"object::constructor: "<<std::endl;
this->value = value;
}
~object(){}
void call()
{
std::cout<<"object::call(): begin"<<std::endl;
std::cout<<value<<std::endl;
std::cout<<"object::call(): end"<<std::endl;
}
};
#endif
This function call:
Handle_Of_Thread_1 = CreateThread(
NULL,
0,
Wrap_Thread_no_1,
&Data_Of_Thread_1, // <== THIS IS A POINTER TO AN int
0,
NULL
);
Passes &Data_Of_Thread_1 (a pointer to an int) to CreateThread(). This is the argument that gets eventually passed to Wrap_Thread_no_1().
Inside that function, you then cast that pointer to a windows_thread* and call a member function through it. This injects Undefined Behavior in your code.
You probably meant to do this instead:
Handle_Of_Thread_1 = CreateThread(NULL, 0, Wrap_Thread_no_1, this, 0, NULL);
// ^^^^

LPTHREAD_START_ROUTINE / array of classes

I wrote some test code like this which compiled and worked fine...
void threadtest()
{
HANDLE hThrd;
DWORD threadId;
int i;
for (i = 0;i < 5;i++)
{
hThrd = CreateThread(
NULL,
0,
ThreadFunc,
(LPVOID)i,
0,
&threadId );
}
// more stuff
}
DWORD WINAPI ThreadFunc(LPVOID n)
{
// stuff
return 0;
}
Then I wanted to modify the code to put the ThreadFunc inside a class and then declare an array of those classes. I thought the code should look like this:
class thread_type
{
public:
DWORD WINAPI ThreadFunc(LPVOID n)
{
// stuff
return 0;
}
};
void threadtest()
{
HANDLE hThrd;
DWORD threadId;
int i;
thread_type *slave;
slave = new thread_type[5];
for (i = 0;i < 5;i++)
{
hThrd = CreateThread(
NULL,
0,
slave[i].ThreadFunc,
(LPVOID)i,
0,
&threadId );
}
// more stuff
}
Unfortunately the compiler complains about the line slave[i].ThreadFunc, I think I may need some special casting but all the permutations I try involving "::" and "&" seem to fail (I'm quite new to C++). The real code has some additional complications which I haven't included for clarity, but I think they are irrelevant.
First problem with the code, that the test class is not descendant of the thread_type. Somehow you need to specify the base class.
Second is, if you are passing function pointer, that shouldn't be thiscall type. The solution is typically this:
struct thread
{
virtual void
run() = 0;
static thread_func(void* param)
{
thread* pThread = (thread*)param;
thread->run();
}
}
struct worker : public thread
{
void
run()
{
(.. code for the thread...)
}
}
void threadtest()
{
HANDLE hThrd;
DWORD threadId;
int i;
thread *slave;
slave = new thread_type[5];
slave[0] = new worker;
slave[1] = new worker;
slave[2] = new worker;
slave[3] = new worker;
slave[4] = new worker;
for (i = 0;i < 5;i++)
{
hThrd = CreateThread(
NULL,
0,
&thread::thread_func,
(LPVOID)slave[i],
0,
&threadId );
}
// more stuff
}
Note that this could is just a reflection, I couldn't compile now, because I don't have here anything to do so, but the logic should be like this.
The following explains the difference between a pointer to a function and a pointer to a member function C++ FAQ Lite. See section 33.2 which explains why what you are doing is a bad idea.