Set thread's "nice level" from creator thread? - c++

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.

Related

Check if current thread is main thread

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.

id of "main" thread in c++

Is there a way in c++ to get the id of the "main" program thread?
I see that std::this_thread::get_id() gets the id of the currently executing thread but I need the id of the main, original program thread. I don't see any function to get this.
The reason is that I have some non thread safe internal functions that must only be called on the original thread of the application so to be safe I want to do :-
assert(std::this_thread::get_id() == std::main_thread::get_id());
But there of course isn't a function to do that, and I can't see any way to get that information.
You could save it while this_thread is still the original thread:
std::thread::id main_thread_id;
int main() {
main_thread_id = std::this_thread::get_id(); // gotcha!
/* go on */
}
This topic seems to be discussed quite a few times here, like in this topic:
Getting a handle to the process main thread
You can find some solutions, but I'd just think the other way round... When starting the new threads, just supply the id of the main thread to them, and store that in a field in the other threads. If that is not going to change throughout the threads' life, you're good to go, you can reference the "main" thread by those handles.

C++ Referencing a boost::thread from its thread function

I'm working with boost threads and I need to reference a thread from its thread function so I can store it in a map with its corresponding thread id. The main idea is that I will be using another thread to gather thread stats by querying the proc table, so I cant use boost::this_thread::get_id(). I need to store the thread so I can call interrupts and joins on specific threads.
The following insert statement doesn't work, but I would have expected this or &this to reference the thread.
Thread function:
workerFunc(){
std::string tid;
tid=boost::lexical_cast<string>(syscall(SYS_gettid));
threadMap.insert(pair<std::string,boost::thread>(tid,this));
}
Currently I have the parent make the insert but wait for the thread to get its thread id, but that is not what a want.
How can I store the thread/a pointer to the thread without using the parent?
By using a functor instead of a function, you can add state to it.
No, you can't directly pass thread object to the function (or functor) that you pass to thread's constructor. It kind of "the egg or the chicken".
The entity that should fill this map is the manager, which creates these thread objects. And why do you have to "wait for the thread to get its thread id"? I don't see such a requirement in the documentation - get_id() is applicable to any "thread of execution", i.e. non-detached thread.

Is it possible from within a thread in C/C++ to get a parent thread id if it wasn't passed in as an argument on pthread_create?

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.

Keep track of pthread

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.