Compare thread IDs using windows api - c

I'm working with windows api threads and I would like to compare thread IDs.
First I create a thread with CreateThread() and store the handle( HANDLE ) and ID ( LPDWORD ) that I get from the function.
Then I get the handle and id from the created thread using GetCurrentThread() and GetThreadId().
I always get different values for both handles and both IDs.
Is there a way to compare threads in a similar fashion as pthread?
I'm doing this to as a debug option to confirm correct execution. I have always gotten correct results from other libraries( pthread.h, threads.h) but not from windows api. It is not a critical problem but I would like to learn the procedure in winapi

Instead of using GetCurrentThread() and GetThreadId(), you can use GetCurrentThreadId() [http://msdn.microsoft.com/en-us/library/windows/desktop/ms683183%28v=vs.85%29.aspx].
As said before, don't use pseudo-HANDLE (returned by GetCurrentThread()) on another thread.
From what I know, there could several different HANDLE to one thread but ID should be an unique identifier.

GetCurrentThread() does not return a real handle. From MSDN:
Retrieves a pseudo handle for the calling thread.
...
A pseudo handle is a special constant that is interpreted as the current thread handle.
You cannot compare this value to the result of CreateThread(). If you are using this value in GetThreadId() from a different thread, you will also not get the ID you want.
You can use DuplicateHandle() on the pseudo handle to retrieve the real handle.

Related

Pthread: How exactly work rwlockattr

I've got a question about "rwlocks", especial about "rwlockattr".
I've got a linked list with several threads working with. Every Member on this list has got a "rwlock". So now I want to set up a rule to secure that threads who want access a write-lock have a higher priority. My intention is to use
int pthread_rwlockattr_setkind_np(pthread_rwlockattr_t *attr,int pref);
So now my Question; Do I need to initialize a "rwlockattr" for every "rwlock" in my linked List or is it enough to set up a global "rwlockattr", initialize it and set up the "PTHREAD_RWLOCK_PREFER_WRITER_NP" rule ?
regards
With every rwlock there is some by default attributes associated with it. For the pthread_rwlock_init() go through this link which will give you more information that how to use rwlock.
You can assign single attribute to your rwlocks. You globally create a single attribute and assign to your rwlocks having the same nature.
Go through this to understand the use of pthread_rwlock.
In general Attributes are to decide the nature of your rwlock.

Selenium windows Handle Return

I am using Selenium to get windows handles. Now something which am curious is on the return type of Handles. Is there a possibility that Handles might return duplicate values and hence they have made it to return Set instead of List. My Initial Assumptions are windows handle might return duplicate values. I feel that it returns Set and not Map because of having two parameters key and values. So they would have made it return a simple Set.
getWindowHandles() is returning Set<String> only in Java. In C# WindowHandles returns ReadOnlyCollection<string> which is wrapper to List<string>.
Window handles can't be duplicated as they are unique identifier for the open windows.

LabVIEW: How to exchange lots of variables between loops?

I have two loops:
One loop gets data from a device and processes it. Scales received variables, calculates extra data.
Second loop visualizes the data and stores it.
There are lots of different variables that need to passed between those two loops - about 50 variables. I need the second loop to have access only to the newest values of the data. It needs to be able to read those variables any time they are needed to be visualized.
What is the best way to share such vector between two loops?
There are various ways of sharing data.
The fastest and simplest is a local variable, however that is rather uncontrolled, and you need to make sure to write them at one place (plus you need an indicator).
One of the most advanced options is creating a class for your data, and use an instance (if you create a by-ref class, otherwise it won't matter), and create a public 'GET' method.
In between you have sevaral other options:
queues
semaphores
property nodes
global variables
shared variables
notifiers
events
TCP-IP
In short there is no best way, it all depends on your skills and application.
As long as you're considering loops within the SAME application, there ARE good and bad ideas, though:
queues (OK, has most features)
notifiers (OK)
events (OK)
FGVs (OK, but keep an eye on massively parallel access hindering exec)
semaphores (that's not data comms)
property nodes (very inefficient, prone to race cond.)
global variables (prone to race cond.)
shared variables (badly implemented by NI, prone to race cond.)
TCP-IP (slow, awkward, affected by firewall config)
The quick and dirty way to do this is to write each value to an indicator in the producer loop - these indicators can be hidden offscreen, or in a page of a tab control, if you don't want to see them - and read a local variable of each one in the consumer loop. However if you have 50 different values it may become hard to maintain this code if you need to change or extend it.
As Ton says there are many different options but my suggestion would be:
Create a cluster control, with named elements, containing all your data
Save this cluster as a typedef
Create a notifier using this cluster as the data type
Bundle the data into the cluster (by name) and write this to the notifier in the producer loop
Read the cluster from the notifier in the consumer loop, unbundle it by name and do what you want with each element.
Using a cluster means you can easily pass it to different subVIs to process different elements if you like, and saving as a typedef means you can add, rename or alter the elements and your code will update to match. In your consumer loop you can use the timeout setting of the notifier read to control the loop timing, if you want. You can also use the notifier to tell the loops when to exit, by force-destroying it and trapping the error.
Two ways:
Use a display loop with SEQ (Single Element Queue)
Use a event structure with User Event. (Do not put two event structures in same loop!! Use another)
Use an enum with case structure and variant to cast the data to expected type.
(Notifier isn't reliable to stream data, because is a lossy scheme. Leave this only to trigger small actions)
If all of your variables can be bundled together in a single cluster to send at once, then you should use a single element queue. If your requirements change later such that the transmission cannot be lossy, then it's a matter of changing the input to the Obtain Queue VI (with a notifier you'd have to swap out all of the VIs). Setting up individual indicators and local variables would be pretty darn tedious. Also, not good style.
If the loops are inside of the same VI then:
The simplest solution would be local variables.
Little bit better to use shared variables.
Better is to use functional global variables (FGVs)
The best solution would be using SEQ (Single Element Queue).
Anyway for better understanding please go trough this paper.

Create a non-blocking timer to erase data

Someone can show me how to create a non-blocking timer to delete data of a struct?
I've this struct:
struct info{
char buf;
int expire;
};
Now, at the end of the expire's value, I need to delete data into my struct. the fact is that in the same time, my program is doing something else. so how can I create this? even avoiding use of signals.
It won't work. The time it takes to delete the structure is most likely much less than the time it would take to arrange for the structure to be deleted later. The reason is that in order to delete the structure later, some structure has to be created to hold the information needed to find the structure later when we get around to deleting it. And then that structure itself will eventually need to be freed. For a task so small, it's not worth the overhead of dispatching.
In a difference case, where the deletion is really complicated, it may be worth it. For example, if the structure contains lists or maps that contain numerous sub-elements that must be traverse to destroy each one, then it might be worth dispatching a thread to do the deletion.
The details vary depending on what platform and threading standard you're using. But the basic idea is that somewhere you have a function that causes a thread to be tasked with running a particular chunk of code.
Update: Hmm, wait, a timer? If code is not going to access it, why not delete it now? And if code is going to access it, why are you setting the timer now? Something's fishy with your question. Don't even think of arranging to have anything deleted until everything is 100% finished with it.
If you don't want to use signals, you're going to need threads of some kind. Any more specific answer will depend on what operating system and toolchain you're using.
I think the motto is to have a timer and if it expires as in case of Client Server logic. You need to delete those entries for which the time is expired. And when a timer expires, you need to delete that data.
If it is yes: Then it can be implemented in couple of ways.
a) Single threaded : You create a sorted queue based on the difference of (interval - now ) logic. So that the shortest span should receive the callback first. You can implement the timer queue using map in C++. Now when your work is over just call the timer function to check if any expired request is there in your queue. If yes, then it would delete that data. So the prototype might look like set_timer( void (pf)(void)); add_timer(void * context, long time_to_expire); to add the timer.
b) Multi-threaded : add_timer logic will be same. It will access the global map and add it after taking lock. This thread will sleep(using conditional variable) for the shortest time in the map. Meanwhile if there is any addition to the timer queue, it will get a notification from the thread which adds the data. Why it needs to sleep on conditional variable, because, it might get a timer which is having lesser interval than the minimum existing already.
So suppose first call was for 5 secs from now
and the second timer is 3 secs from now.
So if the timer thread only sleeps and not on conditional variable, then it will wake up after 5 secs whereas it is expected to wake up after 3 secs.
Hope this clarifies your question.
Cheers,

How do I find a item in ListView control?

My list view contains 3 columns Name, address and phone number.
I want to retrieve an index for a particular name.
I'm using ListView_FindItem macro to find the index number but when my code comes to this line it crashes the program.
It just says Payroll has stopped working. Windows can check online for a solution to the problem.
I'm sure I have passed right handle to the ListView_FindItem macro but I'm not sure about the LVFINDINFO structure.
Here's my code
WCHAR szProcess[80] = {0};
LVFINDINFO item = {LVFI_STRING, (LPCTSTR) szProcess};
//code to find parent handles
...
//code to find index
index = ListView_FindItem(hwndListView, -1, &item);
I'm not sure about the LVFI_STRING flag and I have even tried passing a constant LVFINDINFO structure to ListView_FindItem macro still my program crashes.
Note : The above code is not part of
the payroll application. I mean to say
the payroll application has the
listview and I'm trying to search the
item from other application.
Can some one point me in a right direction ?
Thanks.
Your description is a little unclear, but I interpret it that you are sending LVM_FINDITEM message (via the ListView_FindItem() macro) to a window in a different process.
This simply does not work for this particular Windows message since it passes a pointer to a struct in the calling process which is meaningless when interpreted in the context of the other process (the payroll app that owns the list view).
To solve your problem you could allocate memory in the other process although this is quite a complex task. A commonly cited example of the technique is to be found in the Code Project article, Stealing Program's Memory.
Perhaps a simpler approach would be to use WM_COPYDATA which will marshal string data between processes. If that doesn't have enough flexibility then you'd need to find another IPC mechanism, e.g. named pipes.

Resources