Passing structure to thread using _beginthreadx

#include <iostream> #include <iomanip> #include <stdio.h> #include <windows.h> #include <process.h> using namespace std; HANDLE ghEvents; struct DataStructure { int r[2]; int h; }; unsigned __stdcall f2(void *p) { DataStructure *input = (DataStructure *)p; int i = (int)input->h; cout <<i<<endl; } int main() { HANDLE hThread[8]; DWORD i, dwEvent, dwThreadID; unsigned threadID; DataStructure input; ghEvents = CreateEvent(NULL,FALSE,FALSE,NULL); for (int i = 0; i < 8; i++) { input.h=i; hThread[i] = (HANDLE)_beginthreadex( NULL, 0, f2, (void*)&input, 0, &threadID ); } dwEvent = WaitForMultipleObjects(8,hThread,TRUE,INFINITE); CloseHandle(ghEvents); for (int i = 0; i < 8; i++) { CloseHandle( hThread[i] ); } cin.get(); return 0; }

The output is 77777777 instead of 12345678.

I know i have to pass the input by value and not reference but it keeps giving me an error message, what is the proper way to do it?

-------------Problems Reply------------

This is subsequent to my previous answer as is a better solution if the number of threads is known at compile time.

DataStructure input[8];

...

for (int i = 0; i < 8; i++)
{
input[i].h=i;
hThread[i] = (HANDLE)_beginthreadex( NULL, 0, f2, (void*)&input[i], 0, &threadID );
}

And you need to return a value:

unsigned __stdcall f2(void *p)
{

DataStructure *input = (DataStructure *)p;
int i = input->h;
cout <<i<<endl;
return 0;
}

You are giving each thread the address of the same DataStructure. Your output is non-deterministic. Depending on when each thread gets to run, they may read before, during, or after another iteration of that loop. Meaning, by the time the thread spins up and gets to access input->h, the main thread may have already continued on and changing input.h to the next iteration.

Example:

  • Main - Loop iteration 0 sets input.h to 0.
  • Main - Loop iteration 0 starts Thread 0 with input as a parameter.
  • Main - Loop iteration 1 sets input.h to 1.
  • Main - Loop iteration 1 starts Thread 1 with input as a parameter.
  • Main - Loop iteration 2 sets input.h to 2.
  • Main - Loop iteration 2 starts Thread 2 with input as a parameter.
  • Thread 1 - Starts up.
  • Thread 0 - Starts up.
  • Main - Loop iteration 3 sets input.h to 3.
  • Thread 0 - Reads input->h as 3.
  • Thread 2 - Starts up.
  • Main - Loop iteration 3 starts Thread 3 with input as a parameter.
  • Thread 1 - Reads input->h as 3.
  • Thread 3 - Starts up.
  • Main - Loop iteration 4 sets input.h to 4.
  • Thread 3 - Reads input->h as 4.
  • Thread 2 - Reads input->h as 4.
  • Thread 4 - Starts up.
  • Thread 4 - Reads input->h as 4.

Final Output: 3344

Give each thread a different DataStructure so that they are not trying to read from the same memory address. This way, there is no race-condition. The term refers to the fact that thread start up and order of execution is not guaranteed, so if threads are accessing the same resources without synchronization being done, they will "race".

First point is:

You have no synchronization in place for your datastructure which is being passed to multiple threads, and while these threads are doing something with it, you're already going through the next iteration of the loop and changing the value of your datastructure.

Create a new datastructure inside a the loop to avoid having synchronization issues.

You need to create the data structure for each of the threads as you are overwriting the value of input.h for each of the threads.

So to fix, change it to

DataStructure *input;

...

for (int i = 0; i < 8; i++)
{
input = new DataStructure ;
input->h=i;
hThread[i] = (HANDLE)_beginthreadex( NULL, 0, f2, (void*)input, 0, &threadID );
}

And to avoid a memory leak get the f2 function to delete the input i.e.

unsigned __stdcall f2(void *p)
{

DataStructure *input = (DataStructure *)p;
int i = input->h;
cout <<i<<endl;
delete input;
return 0;
}

note This solution uses dynamic memory allocation as is good solution if the number of threads are unknown at compile time. See my other answer if the number of threads is known.

Category:c# Views:0 Time:2012-01-13

Related post

  • How to pass data between threads? 2009-09-14

    What are ways to pass data between threads in .NET? There are two things I can currently think of: Membervariables, e.g. using the producer-consumer-queue pattern. Using the ParameterizedThreadStart delegate when starting the the thread. (Only works

  • Is it possible to use instanceof when passing objects between Threads? 2010-06-11

    I've run into an issue where instanceof works, and then it doesn't. Going into details is difficult, but I think this might be the problem: Reading this: http://www.theserverside.com/news/thread.tss?thread_id=40229 (search for Thread.currentThread),

  • Passing Structure to function as argument in C 2010-11-04

    I am having this problem and Dont know the reason I have this structure typedef struct { Int32 frameID; Int32 slotIndx; Int32 symNumber; } recControlList; recControlList *recControlListPtr; Datatypes are typedefs. Caller function is : Fun( recControl

  • what is the best way to pass arguments to thread in C windows? 2011-03-02

    Hi I have a thread that uses couple of variables. variables are determined in runtime from argv[]. My options as i see them: make the variables global so the threads can use them (don't need to protect them since the thread doesn't change them). i'm

  • pass structure to kernel local memory 2011-04-17

    I have problem with passing structure to kernel local memory. Here is the kernel kode: typedef struct data { unsigned long wId; // group_id unsigned long iId[1]; // global_item_id } DATA; __kernel void tKernel(__global DATA *x, __local DATA tmp) { in

  • Python passing variable into thread 2011-11-13

    I'm using the threading module to control threads that send data through sockets and what not, however I can't find a suitable solution to pass data into the thread to work with. I've tried things such as Overriding python threading.Thread.run() but

  • Passing structure as parameter in RestApi using JAVA 2014-12-04

    I am basically trying to pass structures (complex objects) as arguments to a rest based service. Uptill now I know pass primitive types in URIs as varname=value&varname2=value. My Question is how to pass structures containing multiple fields to t

  • Passing structures as arguments while using pthread_create() 2009-05-14

    I tried passing a structure as the 4th argument while using pthread_create() with something like this: pthread_create(&tid1, NULL, calca, &t); //t is the struct Now whenever I try to access variables in the structure - t.a, t.b or t.c, I keep

  • Passing Structures by Reference? 2010-03-29

    I am trying to create a linked list, with two seperate lists in one structure. That is, it holds a 'name' and a 'age' value. Then the program can either output the list sorted by name, or sorted by age. So i need two linked lists, essentially. Howeve

  • How to structure a threaded TCP client in Java 2011-03-19

    I need to write a threaded TCP client in Java but am unsure about how to best structure it. I would like the client to run on another thread so as to not block the main thread. Ideally I would create the client on the main thread and then instruct th

  • Passing QModelIndex cross Thread queued connection 2011-07-11

    WMIQuery::wmiquery(WMI::WMITable* table, const QString& query, WMI::ProgressIndicator* progressIndicator) This is the Function signature. and I am calling it through QtConcurrent::run QFuture<quint32> future = QtConcurrent::run(WMI::WMIQuer

  • Pass variables into Thread on the go? 2011-12-19

    I'm not sure if I'm just missing something here, but is it possible to pass a variable into a running Thread in java? The variables may change and may need to be resent into the same thread. Any tutorials on the matter or examples would be great. ---

  • Passing structure with list of structures to function 2012-04-24

    I have a function with prototype: void procedureForEachWave(struct barge *Barge, struct settings *Settings, struct wave *Wave) In another function I have a another structure called threadData, which I use to send information to functions that run on

  • How can I pass structured data to my (F)CGI through Apache? 2009-01-08

    We've got an apache module in place for authentication. If the user is able to authenticate, the REMOTE_USER environment variable is set to their username, where it's available to any CGI they access. I'd like to add a feature/module so that we can g

  • Marshalling in c# ( Passing structure to an unmanaged type ) 2009-04-26

    I have a c++ dll which exposes the following function long func(struct name * myname) { strcpy(myname->firstname,"rakesh"); strcpy(myname->lastname,"agarwal"); return S_OK; } struct name { char firstname[100]; char lastname[100]; } I want to ca

  • Any special autorelease actions for a variable passed from one thread to another(iphone) 2009-09-30

    I have a NSDictionary that is passed from the main thread to a second thread which retains, uses, then releases the variable. What if the main thread autorelease pool is drained while the 2nd thread is still using the variable? Even though I have ret

  • Passing structures using sento() 2009-12-11

    How do I pass following message format from a UDP client to a UDP server? ----------------------------- |Ver|p|fff| length| checksum| ---------------------------- | Customer id | ----------------------------- | Amount | -----------------------------

  • How do I pass transactions between threads for parallel execution? 2010-01-25

    I'd like to execute a task in parallel where each thread needs to have DB access but if one thread fails the transactions in all threads will fail. You can assume that the transaction is active before the threads are created and that it's committed a

  • Passing structure from VC++ to C# 2010-04-15

    I'm using C# DLL in a VC++ application. I have some details in VC++ like PageNumer pageTitle PageDesc BoxDetail I have to pass these to C# DLL. So I made one structure in VC++, then I pass that to C#. But I couldn't do that. Please help me. VC++ Func

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.155 (s). 11 q(s)