Is std::thread::id unique across processes? - c++11

From my experience, it seems that the result of
std::this_thread::get_id()
is unique across process: ids are different from one process to another.
Is this guaranteed by the standard?

std::thread is implemented on top of pthreads in an environment supporting pthreads. So its becomes there is no (portable) guarantee.
From pthread_self manual:
Thread IDs are guaranteed to be unique only within a process. A
thread ID may be reused after a terminated thread has been joined, or
a detached thread has terminated.

The standard grantees that thread ids are unique across different threads, it also says that terminated thread ids might be reused. It doesn't specify processes, and doesn't acknowledged their existence, so, therefore, it doesn't guarantee uniqueness across processes.
30.3.1.1
An object of type thread::id provides a unique identifier for each thread of execution and a single distinct value for all thread objects
that do not represent a thread of execution (30.3.1). Each thread of
execution has an associated thread::id object that is not equal to the
thread::id object of any other thread of execution and that is not
equal to the thread::id object of any std::thread object that does not
represent threads of execution.
thread::id shall be a trivially copyable class (Clause 9). The library may reuse the value of a thread::id of a terminated thread
that can no longer be joined.
The standard also hides away the implementation of a thread::id, it could be a int or something else.

Related

MFC CEvent class member function SetEvent , difference with Thread Lock() function?

what i s the difference between SetEvent() and Thread Lock() function? anyone please help me
Events are used when you want to start/continue processing once a certain task is completed i.e. you want to wait until that event occurs. Other threads can inform the waiting thread about the completion of this task using SetEvent.
On the other hand, critical section is used when you want only one thread to execute a block of code at a time i.e. you want a set of instructions to be executed by one thread without any other thread changing the state at that time. For example, you are inserting an item into a linked list which involves multiple steps, at that time you don't want another thread to come and try to insert one more object into the list. So you block the other thread until first one finishes using critical sections.
Events can be used for inter-process communication, ie synchronising activity amongst different processes. They are typically used for 'signalling' the occurrence of an activity (e.g. file write has finished). More information on events:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686915%28v=vs.85%29.aspx
Critical sections can only be used within a process for synchronizing threads and use a basic lock/unlock concept. They are typically used to protect a resource from multi-threaded access (e.g. a variable). They are very cheap (in CPU terms) to use. The inter-process variant is called a Mutex in Windows. More info:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682530%28v=vs.85%29.aspx

What is Ruby's ThreadGroup for?

I was flicking through the Pickaxe, looking for the documentation on Thread, and came across ThreadGroup.
The documentation describes what it does, but it doesn't explain what it's for.
Is a thread group related to a thread pool, which I assumed Ruby doesn't have?
New threads are created in their parent's ThreadGroup. You can use the ThreadGroup to organize the implicit tree structure given by the parent threads spawning other threads, and use the list instance method to get all threads which have not terminated yet, i.e. to define methods operating on all threads in the group.
Additionaly, you can use enclose to prohibit adding (or removing) threads to this group, if you run untrusted code and want to keep an eye on the threads it spawns.

Forcing context switch in Windows

Is there a way to force a context switch in C++ to a specific thread, assuming I have the thread handle or thread ID?
No, you won't be able to force operating system to run the thread you want. You can use yield to force a context switch though...
yield in Win32 API is function SwitchToThread. If there is no other thread available for running, then a ZERO value will be returned and current thread will keep running anyway.
You can only encourage the Windows thread scheduler to pick a certain thread, you can't force it. You do so first by making the thread block on a synchronization object and signaling it. Secondary by bumping up its priority.
Explicit context switching is supported, you'll have to use fibers. Review SwitchToFiber(). A fiber is not a thread by a long shot, it is similar to a co-routine of old. Fibers' heyday has come and gone, they are not competitive with threads anymore. They have very crappy cpu cache locality and cannot take advantage of multiple cores.
The only way to force a particular thread to run is by using process/thread affinity, but I can't imagine ever having a problem for which this was a reasonable solution.
The only way to force a context switch is to force a thread onto a different processor using affinity.
In other words, what you are trying to do isn't really viable.
Calling SwitchToThread() will result in a context switch if there is another thread ready to run that are eligible to run on this processor. The documentation states it as follows:
If calling the SwitchToThread function
causes the operating system to switch
execution to another thread, the
return value is nonzero.
If there are no other threads ready to
execute, the operating system does not
switch execution to another thread,
and the return value is zero.
You can temporarily bump the priority of the other thread, while looping with Sleep(0) calls: this passes control to other threads. Suppose that the other thread has increased a lock variable and you need to wait until it becomes zero again:
// Wait until other thread releases lock
SetThreadPriority(otherThread, THREAD_PRIORITY_HIGHER);
while (InterlockedRead(&lock) != 0)
Sleep(0);
SetThreadPriority(otherThread, THREAD_PRIORITY_NORMAL);
I would check out the book Concurrent Programming for Windows. The scheduler seems to do a few things worth noting.
Sleep(0) only yields to higher priority threads (or possibly others at the same priority). This means you cannot fix priority inversion situations with just a Sleep(0), where other lower priority threads need to run. You must use SwitchToThread, Sleep a non-zero duration, or fully block on some kernel HANDLE.
You can create two synchronization objects (such as two events) and use the API SignalObjectAndWait.
If the hObjectToWaitOn is non-signaled and your other thread is waiting on the hObjectToSignal, the OS can theoretically perform quick context switch inside this API, before end of time slice.
And if you want the current thread to automatically resume, simply inform a small value (such as 50 or 100) on the dwMilliseconds.

PostThreadMessage usage across threads created in two c++ files

I have a thread created in the main function and PostThreadMessage from ther is invoked with the corresponding thread ID. If one more thread is created in a seperate file how can we invoke PostThreadMessage as we dont know the thread ID which is a parameter for invoking
You have to either:
Store/pass the thread ID (or thread handle) from whatever created the thread to whatever needs to know about the thread; or
Have some way to find the thread via an object it creates. (e.g. If it creates a window with a unique class, you could find that window and then ask the OS which thread owns the window.)
Other than that, there is no magical way to "find a particular thread with no known attributes that was created by another thread that didn't tell anyone about", unless you want to enumerate all threads within your process (but you would have no way to know thread was the right one, unless you did something like #1 or #2 above, and if you do either of them then you don't need to enumerate in the first place).
Note that there will almost always be more threads in your process than the ones you explicitly create, so you cannot just look for "any thread except the two I already know about," because you might pick up a system worker-thread or similar that you should not mess with.

Recycle-safe thread ID's and when thread stack gets freed?

Does the stack reserved/commited for a thread get freed when
the thread terminates
the thread object is destroyed
(i.e. the thread is terminated and all handles to the thread are closed)
?
More broadly, are there significant resources associated with a thread that has terminated, but still exists since there are valid handles to it?
Reason: I need to modify a kind of "scoped singleton", so it doesn't return a single object, but a per-thread object. I cannot rely on thread creation/termination notices, much less on process-wide ones.
At the moment, I store the objects in a map<ThreadID, Object>, with a cache cleanup policy that's suitable for my application. To protect myself from the OS "recycling" thread ID's, I keep an handle to the thread open. (Rec
A side effect would be holding open handles to long-terminated threads in some corner cases.
According to "Windows VIA C/C++" by Richter and Nasarre (A must-have book for any C++ Windwos programmer) p.154:
Terminating a Thread
A thread can be terminated in four
ways:
The thread function returns. (This is highly recommended.)
The thread kills itself by calling the ExitThread function. (Avoid this
method.)
A thread in the same process or in another one calls the TerminateThread
function. (Avoid this method.)
The process containing the thread terminates. (Avoid this method.)
The Thread Function Returns
You should always design your thread
functions so that they return when you
want the thread to terminate. This is
the only way to guarantee that all
your thread's resources are cleaned up
properly.
Having your thread function return
ensures the following:
All C++ objects created in your thread function will be destroyed
properly via their destructors.
The operating system will properly free the memory used by the thread's
stack.
The system will set the thread's exit code (maintained in the thread's
kernel object) to your thread
function's return value.
The system will decrement the usage count of the thread's kernel object.
The ExitThread Function
You can force your thread to terminate by having it call ExitThread:
VOID ExitThread(DWORD dwExitCode);
This function terminates the thread
and causes the operating system to
clean up all the operating system
resources that were used by the
thread. However, your C/C++ resources
(such as C++ class objects) will not
be destroyed. For this reason, it is
much better to simply return from your
thread function instead of calling
ExitThread yourself.
Of course, you use ExitThread's
dwExitCode parameter to tell the
system what to set the thread's exit
code to. The ExitThread function does
not return a value because the thread
has terminated and cannot execute any
more code.
Note The recommended way to have a
thread terminate is by having its
thread function simply return (as
described in the previous section).
However, if you use the method
described in this section, be aware
that the ExitThread function is the
Windows function that kills a thread.
If you are writing C/C++ code, you
should never call ExitThread. Instead,
you should use the C++ run-time
library function _endthreadex. If you
do not use Microsoft's C++ compiler,
your compiler vendor will have its own
alternative to ExitThread. Whatever
this alternative is, you must use it.
The TerminateThread Function
A call to
TerminateThread also kills a thread:
BOOL TerminateThread( HANDLE
hThread, DWORD dwExitCode);
Unlike ExitThread, which always kills
the calling thread, TerminateThread
can kill any thread. The hThread
parameter identifies the handle of the
thread to be terminated. When the
thread terminates, its exit code
becomes the value you passed as the
dwExitCode parameter. Also, the
thread's kernel object has its usage
count decremented.
Note The TerminateThread function is
asynchronous. That is, it tells the
system that you want the thread to
terminate but the thread is not
guaranteed to be killed by the time
the function returns. If you need to
know for sure that the thread has
terminated, you might want to call
WaitForSingleObject or a similar function,
passing the handle of the thread.
A well-designed application never uses
this function because the thread being
terminated receives no notification
that it is dying. The thread cannot
clean up properly, and it cannot
prevent itself from being killed.
Note When a thread dies by returning
or calling ExitThread, the stack for
the thread is destroyed. However, if
TerminateThread is used, the system
does not destroy the thread's stack
until the process that owned the
thread terminates. Microsoft purposely
implemented TerminateThread in this
way. If other still-executing threads
were to reference values on the
forcibly killed thread's stack, these
other threads would raise access
violations. By leaving the killed
thread's stack in memory, other
threads can continue to execute just
fine.
In addition, dynamic-link libraries
(DLLs) usually receive notifications
when a thread is terminating. If a
thread is forcibly killed with
TerminateThread, however, the DLLs do
not receive this notification, which
can prevent proper cleanup.
When a Thread Terminates
The following actions occur when a
thread terminates:
All User object handles owned by the
thread are freed. In Windows, most
objects are owned by the process
containing the thread that creates the
objects. However, a thread owns two
User objects: windows and hooks. When
a thread dies, the system
automatically destroys any windows and
uninstalls any hooks that were created
or installed by the thread. Other
objects are destroyed only when the
owning process terminates.
The thread's exit code changes from
STILL_ACTIVE to the code passed to
ExitThread or TerminateThread.
The state of the thread kernel object
becomes signaled.
If the thread is the last active
thread in the process, the system
considers the process terminated as
well.
The thread kernel object's usage count
is decremented by 1.
When a thread terminates, its
associated thread kernel object
doesn't automatically become freed
until all the outstanding references
to the object are closed.
Once a thread is no longer running,
there isn't much any other thread in
the system can do with the thread's
handle. However, these other threads
can call GetExitCodeThread to check
whether the thread identified by
hThread has terminated and, if it has,
determine its exit code:
BOOL GetExitCodeThread( HANDLE
hThread, PDWORD pdwExitCode);
The exit code value is returned in the
DWORD pointed to by pdwExitCode. If
the thread hasn't terminated when
GetExitCodeThread is called, the
function fills the DWORD with the
STILL_ACTIVE identifier (defined as
0x103). If the function is successful,
TRUE is returned.
Maybe you should use pthread_getspecific, pthread_setspecific and pthread_key_create to manage your per thread singleton.

Resources