How can i check if the current thread is the main thread on linux? It looks like gettid() only returns an pid but it seems that linux does not guarantee the thread with main() always has a const and uniform pid.
The reason for this is that I have an automatic parallelization going on and I want to make sure pthread_create() is not called in a function that is already running on a thread that's created by pthread_create().
For Linux:
If getpid() returns the same result as gettid() it's the main thread.
int i_am_the_main_thread(void)
{
return getpid() == gettid();
}
From man gettid:
gettid() returns the caller's thread ID (TID). In a single-threaded process, the thread ID is equal to the process ID (PID, as returned by getpid(2)). In a multithreaded process, all threads have the same PID, but each one
has a unique TID.
From man clone:
Thread groups were a feature added in Linux 2.4 to support the
POSIX threads notion of a set of threads that share a single
PID. Internally, this shared PID is the so-called thread
group identifier (TGID) for the thread group. Since Linux
2.4, calls to getpid(2) return the TGID of the caller.
The threads within a group can be distinguished by their
(system-wide) unique thread IDs (TID). A new thread's TID is
available as the function result returned to the caller of
clone(), and a thread can obtain its own TID using gettid(2).
What about using pthread_self()?.
This returns the thread_id of the calling thread. With this function, you can store the main thread id (when you know is main) and compare it later with other values returned from pthread_self() to identify if they are the main thread or another one.
Although I think is wiser to have well structured code. Something like functions to be executed in slave threads and other functions to be executed in the master thread. This is a better approach to this kind of problems.
Related
I'm storing information per thread in a map (map's key is the thread ID).
However, I'm wondering if this is really a good idea. I see that every thread has a different ID, but does that really mean "every thread" or just "every live thread". I mean, within the same process, can a new thread use the same ID as an old thread that ended?
I experience that on Android, for two different threads, strangely syscall(__NR_gettid) are different while boost::this_thread::get_id() are identical. Is it a "bug", or is it just likely to occur.
The documentation for pthread (which both std::thread and boost::thread use) says,
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.
http://man7.org/linux/man-pages/man3/pthread_self.3.html
So, yes, a new thread may reuse an ID from a dead thread inside the same process.
On Linux boost::this_thread::get_id returns the result of pthread_self():
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 thread ID returned by pthread_self() is not the same thing as the kernel thread ID returned by a call to gettid(2).
pthread_self() is to get your own thread id. It doesn't seem like you can get the thread id of the thread which spawned you unless it was given to you during spawning. Or is there a way?
No, all threads are equal in POSIX threads, there is no hierarchy. Even the thread that executes main has no special role and can be terminated without effecting the others.
I put up many threads running. At a later time, I'd like to check if these threads are still alive (i.e., not finished yet and not terminated unexpectedly).
What kind of information should I keep track of regarding the threads in the first place. Thread ID, process ID, etc? How should I get these IDs?
When I need to check the liveness of these threads, what functions should I use? Will pthread_kill work here? pthread_kill takes an opaque type pthread_t as parameter, which I believe is typically an unsigned long. Is pthread_t different from a thread ID? I assume a thread ID would pick up an int as its value. In some tutorials on pthread, they assign an integer to a pthread as its ID. Shouldn't the thread get its ID from the operating system?
A thread's entire identity resides in pthread_t
Initializing a thread returns its pthread_t typed ID to its parent
Each thread can get it's own ID with pthread_self()
You can compare thread IDs using the function:int pthread_equal (pthread_t, pthread_t)
So: Maintain a common data structure where you can store thread status as STARTED, RUNNING, FINISHED using the pthread_t IDs and pthread_equal comparison function to differentiate between the threads. The parent sets the value to STARTED when it starts the thread, the thread itself sets its own state to RUNNING, does its work, and sets itself to FINISHED when done. Use a mutex to make sure values are not changed while being read.
EDIT:
You can set up a sort of 'thread destructor' using pthread_cleanup_push:
http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_cleanup_pop.html
i.e. register a routine to be called when the thread exits (either itself, or by cancellation externally). This routine can update the status.
When you call pthread_create, the first argument is a pointer to a pthread_t, to which pthread_create will assign the thread ID of the newly created thread. If you want to get the thread ID of the current thread, use pthread_self(). This is the only identifying piece of information you need for the thread because all threads created this way share the same process ID.
The way you would check whether a thread is alive depends on what you need this information for. If you just want to wait until the thread has completed, you call pthread_join with the thread ID as the first argument and a pointer to a location for the return value of the thread function as the second argument. Unless you detach the threads you create by calling pthread_detach(pthread_self()) in the thread, you need to call pthread_join on them eventually so that they don't continue to hold on to their stack space.
If for some reason you want to do something while the thread is running, you could create a global variable for each thread that that thread changes when it terminates, and check that variable with the main thread. In that case, you would probably want to detach the threads so that you don't also have to join them later.
On linux, we have pthread_kill() to do this. I'm trying to find a Windows counterpart for it.
In other words, given a thread id, is there a way to decide whether the thread is still running or not?
GetExitCodeThread() is the closest I've found, however, it needs thread handle rather than thread id as its parameter.
You should not use a thread id for this purpose: thread ids can be reused, so if you get a thread id, then that thread exits, another thread can be started with that same thread id.
The handle does not have this problem: once a thread terminates, all handles to that thread will reflect the terminated state of the thread.
You can obtain a handle for a thread with a given id using OpenThread; you can then pass that handle to GetExitCodeThread to determine whether the thread has exited.
In short, no, there isn't. You can determine whether a thread with the given identifier exists or not. However, you fundamentally can't determine that the thread you used to refer to using the given ID is still running or not. That's because the thread ID will be recycled after the thread completes.
To track a thread's lifetime, you need to get a thread handle, which will allow you to keep the thread alive for as long as you need. Think of it as a strong VS. weak reference thing. You can use OpenThread() to get a handle to a thread given its ID. You should do this ASAP after you get the ID, then always use the thread handle.
I am working on thread priorities within my application. There is one realtime thread scheduled with SCHED_RR. I use pthread_setschedparam to set this policy and the priority for it. pthread_setschedparam takes the thread id as a first argument, so after creating a thread with boost::thread I can set its realtime priority.
However, another thread should have a certain nice-level, but no realtime scheduling. I can use
pid_t tid;
tid = syscall(SYS_gettid);
int ret = setpriority(PRIO_PROCESS, tid, nicelevel);
to set its nice level to ǹicelevel, but this is working only if I modify the thread function to contain the lines above. Is there a way to set the nice level from the method that creates the thread?
Thanks!
The boost::thread class exposes a public native_handle() method. In a pthreads-based implementation, this method might return a tid (it also might return a pthread_t *, depending on the meaning of handle in this particular case).
If it indeed returns a tid, using it should solve your problem. Otherwise, you'll probably have to relay the value returned by gettid() from the thread function to the global scope, as this answer suggests.