So i'm getting the hang of using c/c++ but i'm still a bit misguided. I'm also trying to learn synchronization at the same time so things aren't going perfect.
So my potential problem here is,
I have a Node object, Node has a method called run. Run creates a pthread and passes a function pointer of a function called compute() as a parameter.
The Compute function has one parameter which is the Node that called Run()
The Compute function will then access a Semaphore (sem_t) that is a field of the Node object passed as a parameter and will call sem_wait(Node.sem) on that semaphore.
If I do this, will the newly created thread that is running the compute function actually call the sem_wait and do the defined behavior. Or will the the process that originally created the Node call sem_wait?
The sem_wait call will execute in the thread in which it was called (as #Jason C points out in his comment). From what you've described that happens in run after the thread has been started, hence sem_wait will be executed in the first thread.
You seem to be thinking that because the Node object is used in both threads that somehow has an effect on which thread will execute a call. It doesn't. Threads share memory space so your Node object can be used in any thread within a process. That's when you start getting into thread safety issues.
Related
According to cppref:
std::notify_all_at_thread_exit provides a mechanism to notify other
threads that a given thread has completely finished, including
destroying all thread_local objects.
I know the exact semantics of std::notify_all_at_thread_exit. What makes me puzzled is:
How to register a callback function that will be called after a given thread has finished and destroyed all of its thread-local objects?
std::notify_all_at_thread_exit takes a condition variable in its first parameter, by reference. When the thread exits, it will call notify_all on that condition variable, waking up threads that are waiting for the condition variable to be notified.
There doesn't appear to be a direct way to truly register a callback for this; you'll likely need to have a thread waiting for the condition variable to be notified (using the same lock as the one passed into std::notify_all_at_thread_exit. When the CV is notified, the thread that's waiting should verify that the wakeup isn't spurious, and then execute the desired code that should be run.
More info about how this is implemented:
At least on Google's libcxx, std::notify_all_at_thread_exit calls __thread_struct_imp::notify_all_at_thread_exit, which stores a pair with the parameters to a vector (_Notify). Upon thread death, the destructor of __thread_struct_imp iterates over this vector and notifies all of the condition variables that have been registered in this way.
Meanwhile, GNU stdc++ uses a similar approach: A notifier object is created, it's registered with __at_thread_exit, it's designed to call its destructor when run at thread exit, and the destructor actually performs the notification process. I'd need to investigate __at_thread_exit more closely as I don't understand its inner workings fully just yet.
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.
If I am right, the std::async uses a new thread and calls the method in it. I was wondering what happens if the main thread or the parent thread dies. Does the thread controlling the async method dies as well.
There is no concept of a "parent" thread in C++, each thread is independent of the one that it was created by. However, the main thread is special and if it returns from main() or calls exit() then the entire application is terminated even if other threads are still running. Once that happens, the program has undefined behaviour if the still-running threads access any global variables or automatic objects that were on the main thread's stack, or use any standard library objects or call any function not permitted in signal handlers.
In short, do not let other threads run after main completes if you expect sensible results.
I have the following code which initiate the thread.
int iNMHandleThread = 1;
HANDLE hNMHandle = 0;
hNMHandle = CreateThread( NULL, 0, NMHandle, &iNMHandleThread, 0, NULL);
if ( hNMHandle == NULL)
ExitProcess(iNMHandleThread);
My question is
What will happened if I run this code while the thread already in the running state.
I want to initiate the multiple independent threads of NMHandle kindly give me some hints to solve this problem.
Each time you call CreateThread, a new thread is started that is independent of any other currently-running threads. Whether your "NMHandle" function is capable of running on more than one thread at a time is up to you: for example, does it rely on any global state?
What will happened if I run this code while the thread already in the running state.
Another thread will start with the function NMHandle, independent of the other one.
I want to initiate the multiple independent threads of NMHandle kindly give me some hints to solve this problem.
This code actually creates an independent thread. Create a loop if you want to create multiple threads executing the function NMHandle. If you need the thread handles later (e.g. waiting for a thread to end), you have to store them somewhere.
Make sure that NMHandle is thread-safe. If you don't know what that means, you shouldn't start multithreaded programming yet!
And another hint: You're passing a pointer to the local stack variable iNMHandleThread to the thread. As soon as the function returns, the variable content might not have its expected value anymore - you should rather pass the number by value (CreateThread( NULL, 0, NMHandle, (void*)iNMHandleThread, 0, NULL);).
CreateThread creates a new thread. The new thread obviously can't be in the running state before - it doesn't have a state before it's created. Compare the simple statement int i = 42; - There's no prior value of i before 42, because the object doesn't exist yet. Obviously the old thread that calls CreateThread() must be running - otherwise it couldn't have run to the line that calls CreateThread() !
Every time you call CreateThread, you will get a new thread. You will also get a new thread handle and ID for every call. So you can't store them all in int iNMHandleThread or HANDLE hNMHandle. Consider a std::list<int> NmThreadIDs and std::list<HANDLE> NmThreadHandles;.
Furthermore, all new threads will start by calling NMHandle(). Is that function thread-safe? That is to say, will that function work properly when executed by two threads at the same time, or interleaved, or in any other random order? Mechanisms like mutexes and critical sections can be used to exclude some unsafe orders of execution.
I am working on a multithreaded program using C++ and Boost. I am using a helper thread to eagerly initialize a resource asynchronously. If I detach the thread and all references to the thread go out of scope, have I leaked any resources? Or does the thread clean-up after itself (i.e. it's stack and any other system resources needed for the itself)?
From what I can see in the docs (and what I recall from pthreads 8 years ago), there's not explicit "destory thread" call that needs to be made.
I would like the thread to execute asynchronously and when it comes time to use the resource, I will check if an error has occured. The rough bit of code would look something like:
//Assume this won't get called frequently enough that next_resource won't get promoted
//before the thread finishes.
PromoteResource() {
current_resource_ptr = next_resource_ptr;
next_resource_ptr.reset(new Resource());
callable = bind(Resource::Initialize, next_resource); //not correct syntax, but I hope it's clear
boost::thread t(callable);
t.start();
}
Of course--I understand that normal memory-handling problems still exist (forget to delete, bad exception handling, etc)... I just need confirmation that the thread itself isn't a "leak".
Edit: A point of clarification, I want to make sure this isn't technically a leak:
void Run() {
sleep(10 seconds);
}
void DoSomething(...) {
thread t(Run);
t.run();
} //thread detaches, will clean itself up--the thread itself isn't a 'leak'?
I'm fairly certain everything is cleaned up after 10 seconds-ish, but I want to be absolutely certain.
The thread's stack gets cleaned up when it exits, but not anything else. This means that anything it allocated on the heap or anywhere else (in pre-existing data structures, for example) will get left when it quits.
Additionally any OS-level objects (file handle, socket etc) will be left lying around (unless you're using a wrapper object which closes them in its destructor).
But programs which frequently create / destroy threads should probably mostly free everything that they allocate in the same thread as it's the only way of keeping the programmer sane.
If I'm not mistaken, on Windows Xp all resources used by a process will be released when the process terminates, but that isn't true for threads.
Yes, the resources are automatically released upon thread termination. This is a perfectly normal and acceptable thing to do to have a background thread.
To clean up after a thread you must either join it, or detach it (in which case you can no longer join it).
Here's a quote from the boost thread docs that somewhat explains that (but not exactly).
When the boost::thread object that
represents a thread of execution is
destroyed the thread becomes detached.
Once a thread is detached, it will
continue executing until the
invocation of the function or callable
object supplied on construction has
completed, or the program is
terminated. A thread can also be
detached by explicitly invoking the
detach() member function on the
boost::thread object. In this case,
the boost::thread object ceases to
represent the now-detached thread, and
instead represents Not-a-Thread.
In order to wait for a thread of
execution to finish, the join() or
timed_join() member functions of the
boost::thread object must be used.
join() will block the calling thread
until the thread represented by the
boost::thread object has completed. If
the thread of execution represented by
the boost::thread object has already
completed, or the boost::thread object
represents Not-a-Thread, then join()
returns immediately. timed_join() is
similar, except that a call to
timed_join() will also return if the
thread being waited for does not
complete when the specified time has
elapsed.
In Win32, as soon as the thread's main function, called ThreadProc in the documentation, finishes, the thread is cleaned up. Any resources allocated by you inside the ThreadProc you'll need to clean up explicitly, of course.