user2426357
user2426357

Reputation: 31

Synchronizing a thread with two running threads, c++, windows

I am a newbie in multithread programming and this is my first post here! So please bear with me.

I have two cameras which I would like to track an object simultaneously (two independent threads) and output its position to the main function or perhaps a third thread. Using the position of the object from each camera, the 3D position of the object should then be calculated. Let's say the first camera outputs x1 and y1, the second camera outputs x2 and y2 and these should be used to estimate x, y, and z.

I was thinking of defining x1, y1, x2 and y2 as global variables so that they are easily accessible for the third thread. But the problem is that the third thread should be synchronized with the first 2 threads. The third thread doesn't change the content of x1, y1, x2 and y2. It only uses these values to obtain x, y and z. But if the value x1 and y1 is updated and x2 and y2 are not yet updated, I want the third thread to pause until the x2 and y2 is updated. Or in other words, I want the third thread to use x1, y1, x2 and y2 that are ideally obtained at a time point t, or during a very short period of time.

I appreciate any suggestions on how to approach this problem. I am thinking of using CreateThread(). Is there an easier way? Is it a good idea to use global variable in multithread programming? Is it a good idea to output global variables t1 and t2 (system time) from thread 1 and 2 respectively, and compare them in the third thread? One problem with this approach might be that since both threads 1 and 2 are doing the same thing, it takes let's say T second for them to complete their task and therefore there is always a fixed lag between these threads which might be longer that what we want. And as a result, thread 3 would never find x1, y1, x2 and y2 which are obtained very close in time!

NOTE: I am using windows 7, visual studio 2010, programming language C++.

Upvotes: 0

Views: 1444

Answers (1)

ScottMcP-MVP
ScottMcP-MVP

Reputation: 10415

Thread 1 can SetEvent(event1) and thread 2 can SetEvent(event2). Thread 3 uses WaitForMultipleObjects to wait until both events have been set. WaitForMultipleObjects suspends the calling thread and then returns when both events are set.

Upvotes: 1

Related Questions