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

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.

Related

Confused about pthreads

First, I am new to pthreads, so if I completely misunderstood, please just let me know.
I had searched for the proper method of returning values and came across this link How to return a value from thread in C and https://linuxprograms.wordpress.com/category/pipes/ .
So I can share locations controlled by the starting thread OR pipe information, but the last value can't be put on some stack? Why can't I return in the same way that a program does when called by a shell (such as bash)?
(From what I understand, it would be possible to have a regular return value if it was C++, but (according to something I read I think here perhaps https://computing.llnl.gov/tutorials/pthreads/) POSIX isn't completely defined for C++, just C.)
Take a look at pthread_exit and pthread_join.
When you are done with your thread you can call pthread_exit(void* retval)
The pthread_exit() function terminates the calling thread and returns
a value via retval that (if the
thread is joinable) is available to another thread in the same process that calls pthread_join(3).
This call to pthread_exit will stop your thread and, as it says, store the return value where pthread_join can get to it and place it in its second argument: int pthread_join(pthread_t thread, void **retval);
When you call pthread_join(tid, &returnVal); where tid is a pthread_t, returnVal will now hold a pointer to the value returned given to pthread_exit
This allows you to pass data out of threads on their exit.
Each thread has its own stack and local environment with the parent process. Your main process creates one thread (the main thread) and your code runs under it. Any other threads you create, get the same treatment: each gets a stack, a thread context, thread local storage (where applicable) and there is no common stack to return a value.
When you join a thread you started, what happens is you are actually waiting for it to finish executing. This will unblock the wait, but will not return any user value since typically, the thread, its stack, and all of its environment within the process is destroyed.
While threads are running, they can communicate with one another in the ways you mentioned, and they can also read/write to common memory locations as long as you use a synchronization mechanism to serialize those accesses.
If you must have a return value from your thread, then you might want to encapsulate it in a class, pass it the class instance on start, then just before the thread exits, it can leave a "return value" in a member of this class so you can examine it after the class "run" or "start" method (the one that actually runs the thread) returns.
Hope this helps.

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.

Given a thread id, how to decide it's still running or not on Windows

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.

Set thread's "nice level" from creator thread?

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.