I know it is possible to get the id of a thread by using GetCurrentThreadId(), however, is it possible to actually set the thread id? If so, how?
Ex: I want to change the thread ID of a thread from 5432 to 1234.
The ThreadID is assigned by Windows from internal tables. You cannot change it.
As stated in the documentation
Until the thread terminates, the thread identifier uniquely identifies the thread throughout the system.
If thread ID modification would be possible, then you should disable creating new threads until you ensure that your ID is not used by anyone else. You will admit that is not realistic.
Related
I have a multi-threaded embedded architecture that contains 6 application specific processes which are executed when the initialization process is executed. Likewise, each have their own number of threads that are running.
What i want to do is suspend the running threads of 1 particular process based on whether the device is connected to the pc or not.
I have tried searching around and the closest i've found to what im looking for is the following: How to obtain list of thread handles from a win32 process?
However, that code returns the list of all running threads. This wont work for me since im trying to suspend all obtained threads, assuming they have been obtained from the same process, thus i do not check which process they belong too.
Likewise, i am obtaining the list of running threads of a processes in another process.
Is there an existing method from windows that allows such control, or am i stuck with having to identify which threads i need to suspend from the entire list?
Instead of trying to forcefully suspend threads (which is likely to bring you trouble when you suspend in "not so lucky moment") you'd rather use a named CreateEvent() with manual reset.
Named events are easily shared between processes. You simply CreateEvent() again with the same name. The typical name for event would be MyCompany_MyProduct_MyFeature_EventName to prevent accidental collisions.
When you WaitForSingleObject() on "set" event, the wait is immediately satisfied.
When you wait on "reset" event, the wait suspends your thread until event is set.
Your first application will have its thread(s) wait on event when they're not doing any work and therefore safe to suspend.
You will set and reset event from second application to control the first application.
This way, you don't need to enumerate threads, and it's more robust.
I used pthread_create created a child thread for http requested,after i get the data i want to call the main thread to do some update of UI.
pthread_detach();
pthread_exit();
pthread_join();
The three function which can use for that?Why?
Is there any warm-hearted person to solve my confusion? A lot of thanks!
The honest answer is none of the above. There is no way to call the main thread from the child thread, but that does not mean you can't do what you are trying to.
A child thread shares the same memory space as the parent thread. What you need to do is create a way for the child thread to inform the parent that it wants to send a message to the user (UI). This could be done a number of different ways, but a simple method would be to provide a function that just takes the message you want to send and puts it onto a queue.
The main thread would just need to check that queue occasionally for any messages and pull them off when it sees one on there to put onto the UI.
You would of course need to make sure that pushing/popping from that queue was controlled with a mutex lock, but since we're talking about messages to the user it shouldn't be something you're doing too often and should not cause any real performance problems.
As I mentioned, this is only one idea for how you could do this. While there are many ways, the basic idea is that the threads need a way to communicate with each other.
I am a newbee to linux. Right now I am following "Advanced Linux book"
I know when we create a new thread from a process, it gets inherited from the main thread of the process.
Let's say I created a thread pt1 from pt. Then pt1 inherits the environment,code,signal mask.
The only thing that it doesn't share is "set of pending of signals" for the new thread is cleared.
I want to know what more attributes are not shared between the threads of the same process.
Any help is thankful
Threads in the same process share:
Process instructions
Most data
open files (descriptors)
signals and signal handlers
current working directory
User and group id
Each thread has a unique:
Thread ID
set of registers, stack pointer
stack for local variables, return addresses
signal mask
priority
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.
I am using a static library; it has a function which uses the current time and creates a unique id, which is then inserted into my database. This number should be unique in my database table.
There are two processes running in parallel. Sometimes they simultaneously call this function, and the same number is generated. I get an integrity violation when this happens.
I am thinking to use the process id, the thread id, and the current time. Is this combination unique?
Platform: Windows XP
Use the database to generate them. How to do that depends on the database, but Postgres calls them sequences for an example.
The process/thread id will be unique if the programs are running simultaneously as the OS needs to differentiate them. But the system does reuse ids.
So, for your situation, yes, its a good idea to add either process id or thread id into your marker, tho I don't think you'd need both.
On Windows, thread Ids are unique throughout the system. See this MSDN library article:
http://msdn.microsoft.com/en-us/library/ms686746%28v=VS.85%29.aspx
The CreateThread and CreateRemoteThread functions also return an identifier that uniquely identifies the thread throughout the system. A thread can use the GetCurrentThreadId function to get its own thread identifier. The identifiers are valid from the time the thread is created until the thread has been terminated. Note that no thread identifier will ever be 0.
The combination of process ID, thread ID and time is unfortunately not guaranteed to be unique. The OS may reuse process IDs and thread IDs once the threads and processes they referred to have terminated. Also, the user may set the clock back, so the same time occurs twice. As others have said, I'd ask the database for a unique ID. Oracle has sequences, MySQL has auto-increment columns, other databases have similar mechanisms.
Whilst the process id and thread id will be unique it would be better to use the database to generate the unique id for you (as R. Pate suggests) if only because you're potentially limiting your scalability unless you also include a unique machine id as well...
Though it's probably reasonably unlikely that one of your processes running on machine A will have the same process id and thread id as one of your processes running on machine B those are always the kinds of bugs that end up getting people out of bed at 4am to deal with the support call...
Well, adding process id and thread id could possibly lead to the same number
pid= 100, tid= 104
pid= 108, tid= 96
Not quite likely but possible.
So for near safe ids, you'll need at least a 64 bit ID field like
ULONG64 id = ((ULONG64)(pid&0xffff) << 48) | ((ULONG64)(tid&0xffff) << 32) | (timestamp & 0xffffffff);
(however, this still does not guarantee uniqueness as it assumes that thread ids don't overlap in a way with process ids that they neutralize 16-bit values, but I don't think I ever saw PIDs over 65536 and unless you are creating thousands of threads, the thread IDs will not wrap around in this value before the timestamp jumps).