getting a thread state in c++/windows - c++

There must be a function that gets the current status of a thread in the system because
there is this application: http://www.softwareverify.com/cpp/thread-status-monitor/index.html
It must be using some sort of API function or something...
How can I get a thread state myself in C++/Windows?
thanks :)
(this is my last question for today. I promise :))

That's done via Toolhelp library, check information at MSDN : http://msdn.microsoft.com/en-us/library/ms686780%28v=VS.85%29.aspx

You can use the following examples to get the running processes and, when you have a process ID, the threads.
Taking a Snapshot and Viewing Processes
Traversing the Thread List
EDIT: After getting the handle to the thread(s) you are interested in you can call GetExitCodeThread but that will only tell you if the thread is STILL_ACTIVE until it ends, when you can find the exit code.
While searching for the additional information for your comment I also came across this thread on SO which might be of interest to you.

You get the most bang out of WMI, Win32_Thread class. The linked article has a link to the C++ code you need. Experiment with the WMI Code Creator tool.

Related

changing threads standard input and output

I have an application that creates two threads. (thread_1 for a Qt GUI and thread_2 for an app that runs a TCL interpreter).
I want thread_1 (Qt GUI) to create a command and send it to thread_2 (TCL interpreter).
I'm thinking of connecting thread_1's stdout to thread_2's stdin, and I don't know how to do it ?
if you know how to do it or can suggest different way of work, I'd appreciate your help.
The solution I propose requires to set up 2 std::queue<> or std::list to let each thread pass a message to the other one and vice versa. The simplest way is to have each thread setup its own incoming message queue, and let other threads get a pointer to it. First you need a synchronized version of the queue datatype: as I gave in the comment, there's an implementation there.
Then you only need to upgrade your thread class (or runnable class, or whatever you're using as an abstraction of a task) with one such queue available internally, and a send method publicly accessible so that other tasks may post a message to it. Your task will then have to periodically check that queue for incoming message, and eventually process it.
NB: I got that page from stack overflow itself, since the blog owner is a member of this community. See that page talking about queue synchronization issue.
I am not sure why you would like to go through standard input and output here, but I think the issue might be much simpler than you think. I would just personally use the qt signal-slot mechanism as follows:
connect(guiThreadSender, SIGNAL(sendCommand(const QByteArray&)),
tclThreadReceiver, SLOT(handleCommand(const QByteArray&)));

Thread Status in Linux

I tried looking for a thread on this subject, however couldn't find one. So posting this question.
Assume, I have created couple of threads in C++ in Linux and the code is running.
Now I would like to monitor the process and the threads of the process using a shell script and do some additional processing.
Also I would need the amount of CPU and Memory being used by each thread. I know that a thread is associated to a process, however my requirement is to identify the resources utilized by this thread.
I couldn't find the exact way to identify the threads associated to a process. I tried using PS however I couldn't find any clues. Running RHEL.
From a man page of ps:
To get info about threads:
ps -eLf
ps axms
The manpage for ps might give you more clues.
In particular, it should tell you that -L shows threads, and -o %cpu,%mem will display the amount of CPU and memory being used.
Note that memory is associated with the process, not with any thread, so there is no concept of "memory used by each thread".
Apart from using Linux commands you can use Generic Memory Manager library. Here it defined ThreadingModel class.

need help in UI threads in C++

I'm using UI threads and I built one thread with message map and it works fine, the problem is when I'm tring to create another thread from the first one.
When I'm getting to this line:
this->PostThreadMessage(WM_MYTHREADMESSAGE,0,0);
I'm getting the next message:
"No symbols are loaded for any call stack frame. The source code cannot be displayed"
I dont know if its could be the reason for the problem but I have built two message maps, one for each thread, I don't know if its ok to do so.
The question is difficult to understand. I'm assuming that you're stepping through your program in the debugger, and you get to that PostThreadMessage line.
If you choose Step Into, the debugger will try to step into the PostThreadMessage call (or the framework wrapper, depending on the type of this). Since PostThreadMessage is a system call, it's likely you don't have symbols for that code. The debugger will just show you disassembly. You can try to use the Microsoft symbol server, but I don't see much point in trying to trace into PostThreadMessage. If the parameters are right, it's going to post the message to the specified thread's queue. Not much to see there.
Posting message to other threads is tricky business. Most Windows programs, even multithreaded ones, typically keep all the UI work to a single thread. It can be done, but there are a lot of caveats and it's usually not worth the pain.
So there are couple of things:
if you want to notify the UI thread from the worker thread, then you should not use PostThreadMessage, here is why.
When this->PostThreadMessage(...) called in a member function of thread A, the message will be sent to thread A, because this points to CWinThread of A. You have to get a pointer to the other thread to post a message to it.
Finally if you want to notify your UI thread, use PostMessage to send a message to the window created by that thread. Add a corresponding handler to the window message map.
Hope this helps

What is an easy way to test whether any process of a given id is presently running on Linux?

In C++, I have a resource that is tied to a pid. Sometimes the process associated with that pid exits abnormally and leaks the resource.
Therefore, I'm thinking of putting the pid in the file that records the resource as being in use. Then when I go to get a resource, if I see an item as registered as being in use, I would search to see whether a process matching the pid is currently running, and if not, clean up the leaked resource.
I realize there is a very small probability that a new unrealated pid is now sharing the same number, but this is better than leaking with no clean up I have now.
Alternatively, perhaps there is a better solution for this, if so, please suggest, otherwise, I'll pursue the pid recording.
Further details: The resource is a port number for communication between a client and a server over tcp. Only one instance of the client may use a given port number on a machine. The port numbers are taken from a range of available port numbers to use. While the client is running, it notes the port number it is using in a special file on disk and then cleans this entry up on exit. For abnormal exit, this does not always get cleaned up and the port number is left annotated as being in use, when it is no longer being used.
To check for existence of process with a given id, use kill(pid,0) (I assume you are on POSIX system). See man 2 kill for details.
Also, you can use waitpid call to be notified when the process finishes.
I would recommend you use some kind of OS resource, not a PID. Mutexes, semaphores, delete-on-close files. All of these are cleaned up by the OS when a process exits.
On Windows, I would recommend a named mutex.
On Linux, I would recommend using flock on a file.
How about a master process that starts your process (the one which terminates abnormally) waits for your process to crash (waitpid) and spawns it again when waitpid returns.
while(1) {
fork exec
waitpid
}
The problem domain isn't clear, unfortunately, you could try re-explaining it in some other way.
But if I understand you correctly, you could create a map like
std::map< ProcessId, boost::shared_ptr<Resource> > map;
// `Resource` here references to some abstract resource type
// and `ProcessId` on Windows system would be basically a DWORD
and in this case you simply have to list every running process (this can be done via EnumProcesses call on Windows) and remove every entry with inappropriate id from your map. After doing this you would have only valid process-resource pairs left. This action can be repeated every YY seconds depending on your needs.
Note that in this case removing an item from your map would basically call the corresponding destructor (because, if your resource is not being used in your code somewhere else, it's reference count would drop to zero).
The API that achieves that on windows are OpenProcess which takes process ID as input, and GetExitCodeProcess which returns STILL_ACTIVE when the process is, well, still active. You could also use any Wait function with zero timeout, but this API seems somewhat cleaner.
As other answers note, however, this doesn't seem a promising road to take. We might be able to give more focused advice if you provide more scenario details. What is your platform? What is the leaked resource exactly? Do you have access to the leaking app code? Can you wrap it in a high-level try-catch with some cleanup? If not, maybe wait on the leaker to finish with a dedicated thread (or dedicated process altogether)? Any detail you provide might help.

C++ WxWidgets: Single log window for messages from Multiple Threads

What's the best/proper method to collect log messages from multiple threads and have them all be displayed using a window? (while the threads are running).
I am currently trying to redirect stdout (cout) in to a wxTextCtrl but failing miserably when attempting to do so over multiple threads. Any help would be appreciated.
Logging has had a few major updates recently in the wxWidgets trunk, you can read about them here. One of them is to add support for logging from threads other than the main thread.
In what way is it failing? I'm not familiar with the wxTextCtrl, but unless it has built in synchronization (ie. its thread safe) that could be a big issue. The simplest way to protect a single resource like this is via a named 'mutex'. The following example is what you can do in each thread to make sure that only one accesses this resource (the output window) at a time.
// In each thread's initialization:
HANDLE mutexHandle = CreateMutex(0,FALSE,"__my_protecting_mutex__");
// Whenever you use the debug output:
WaitForSingleObject(mutexHandle, /* Timeout if you like. */ 0xFFFFFFFF );
// Do our printing here.
ReleaseMutex(mutexHandle);
// In each thread's cleanup:
CloseHandle(mutexHandle);
So this basically guarantees that only one thread can be in between the wait and the release. Now if your issue is actually routing to the wxTextCtrl, I would need some more details.
Edit: I just realized that what I posted is Windows specific, and maybe you aren't on windows! If you aren't I don't have experience with other platform's synchronization methods, but boost has some generic libraries which are not platform specific.