Will a thread be restarted again if it encounters the thread_create statement again? - pthreads

I am using pthreads and i have this doubt whether a thread will be restarted again if it encounters the same create statement that created it?

Will a thread be restarted again if it encounters the thread_create statement again?
It'll create a new thread regardless of whether it's called by thread that itself was created via pthread_create.
Lets say i have a thread t1. What happens if encounters the create statement, pthread_create(&t1,NULL,func,NULL). How can a new thread be created if i have a unique thread identifier , say the name t1?
In this case, you are still creating new thread but just reusing/overwriting the previous thread identifier t1. Which means you can only call pthread_join on the second you created but lose the ability to pthread_join, change attributes of the first thread, and so on on the first thread. Note that this is still valid. But if this is your use-case, you are probably better off creating detached threads (either by setting the attribute before creating the first thread or by calling pthread_detach from the thread function). A detached thread can't be joined and whose resources are freed when the thread exits (i.e., either by calling pthread_exit or by returning from the thread function).

Related

What is the pthread's join prerequisite

With pthread, we cannot join any thread.
What is the prerequisite and why is it there?
According to : https://man7.org/linux/man-pages/man3/pthread_join.3.html
The pthread_join() function waits for the thread specified by
thread to terminate. If that thread has already terminated, then
pthread_join() returns immediately. The thread specified by
thread must be joinable.
The pthread_join() function makes the calling thread wait for the end of another thread (which thread identifier is passed as first parameter). By default, any thread is joinable when you call pthread_create(). If you want to make a thread non joinable, you can specify this behaviour by passing some attributes to the pthread_create() function (cf. pthread_attr_setdetachstate()).

Context switches on iOS using "performSelectorOnMainThread"

I have weird threading issues on iOS. Consider a simple method like this:
- (BOOL)doSomething
{
[self doA];
[self doB];
}
This method should only run in context of the main thread. I need to call this method from a worker thread. I use performSelectorOnMainThread for this purpose.
If I do everything as explained here. Can a context switch happen between doA and `doB?
(I don't think so, I just want to make sure that my understanding is right here)
By "context switch" I assume you mean the main thread switching to some other main thread event (as you could always switch to another worker thread at any time).
However, main thread will finish all of doSomething before doing anything else.
Excerpt from performSelectorOnMainThread:
This method queues the message on the run loop of the main thread
using the common run loop modes—that is, the modes associated with the
NSRunLoopCommonModes constant. As part of its normal run loop
processing, the main thread dequeues the message (assuming it is
running in one of the common run loop modes) and invokes the desired
method. Multiple calls to this method from the same thread cause the
corresponding selectors to be queued and performed in the same same
order in which the calls were made.

Pthread: Why people bother using pthread_exit?

As far as I understand, pthread_exit() exactly equals to return when you need terminate a thread with a return value. When people can use the consistent way, i.e. return, to do the job why Pthread define such a duplicated interface?
Two reasons that come to my mind: pthread_exit
Allows you to exit a thread from any depth in the call stack.
Must be called on the main thread if the TLS keys for the main thread are to have their free functions called. And here as well: "Any cancellation cleanup handlers that have been pushed and not yet popped are popped in the reverse order that they were pushed and then executed. After all cancellation cleanup handlers have been executed, if the thread has any thread-specific data, appropriate destructor functions will be called in an unspecified order... An implicit call to pthread_exit() is made when a thread other than the thread in which main() was first invoked returns from the start routine that was used to create it. The function's return value serves as the thread's exit status."
If you're going to call pthread_exit a duplicated interface, then you should also call exit() a duplicated interface, since you could exit the program at an arbitrary point. You probably want to call pthread_exit() when you have some sort of error condition where you simply cannot continue. Or, alternatively, you've found whatever value you're looking for inside of the thread.
As for it's real existence, according to the documentation:
An implicit call to pthread_exit() is made when a thread other than the thread in which main() was first invoked returns from the start routine that was used to create it. The function's return value serves as the thread's exit status.
So if you did a return <some pointer> from the thread, or simply reached the end, pthread_exit() would be called anyway. It's the same with exiting from main(), if you return 0 you're actually calling exit(0). The function has to exist, otherwise the kernel would not have a way of determining if the thread exited.

Does pthread_detach free up the stack allocated to the child thread, after the child thread as exited

I have used pthread_detach inorder to free up the stack allocated to the child thread, but this is not working, I guess it does not free up the memory.....
I don't want to use pthread_join. I know join assures me of freeing up the stack for child, but, I don't want the parent to hang up until the child thread terminates, I want my parent to do some other work in the mean time. So, I have used detach, as it will not block the parent thread.
Please, help me. I have been stuck..
this is not working
Yes it is. You are likely mis-interpreting your observations.
I want my parent to do some other work in the mean time
That's usually the reason to create threads in the first place, and you can do that:
pthread_create(...);
do_some_work(); // both current and new threads work in parallel
pthread_join(...); // wait for both threads to finish
report_results();
I don't want to use pthread_join. I know join assures me of freeing up the stack for child
Above statement is false: it assures no such thing. A common implementation will cache the now available child stack for reuse (in case you'll create another thread shortly).
YES - according to http://cursuri.cs.pub.ro/~apc/2003/resources/pthreads/uguide/users-16.htm it frees memory either when the thread ends or immediately if the thread has already ended...
As you don't provide any clue as how you determine that the memory is not freed up I can only assume that the method you use to determine it is not sufficient...

How to kill a thread in delphi?

In delphi, a method in TThread is terminate. It seems a subthread can not kill another thread by calling terminate or free.
For example
A(main form), B (a thread unit), C (another form).
B is sending data to main form and C (by calling syncronize), we tried to terminate B within C while B is executing by calling B.terminate. But this method does not work and B is still working until it ends in execute method.
Please help. Thank you in advance.
You have to check for Terminate in the thread for this to work. For instance:
procedure TMyThread.Execute;
begin
while not Terminated do begin
//Here you do a chunk of your work.
//It's important to have chunks small enough so that "while not Terminated"
//gets checked often enough.
end;
//Here you finalize everything before thread terminates
end;
With this, you can call
MyThread.Terminate;
And it'll terminate as soon as it finishes processing another chunk of work. This is called "graceful thread termination" because the thread itself is given a chance to finish any work and prepare for termination.
There is another method, called 'forced termination'. You can call:
TerminateThread(MyThread.Handle);
When you do this, Windows forcefully stops any activity in the thread. This does not require checking for "Terminated" in the thread, but potentially can be extremely dangerous, because you're killing thread in the middle of operation. Your application might crash after that.
That's why you never use TerminateThread until you're absolutely sure you have all the possible consequences figured out. Currently you don't, so use the first method.
Actually,
currently most voted answer to this question is incorrect (so as 34 upvoters...) in regard how to forcefully kill a thread.
You do not use ThreadId as a parameter to TerminateThread procedure. Using ThreadId will cause most likely an "Invalid handle" error or in worse case scenerio - will kill a different thread.
You should pass a thread handle as a parameter:
TerminateThread(MyThread.Handle);
More about differences between thread's handle and id can be found here.
Edit
Seems #himself corrected his mistake after seeing my answer, so this is no longer relevant.
Terminate does not kill a thread; it sets the Terminated property to inform the thread that it needs to terminate. It's the thread's responsibility to watch for Terminated and shut itself down gracefully.
All the Terminate method does is it sets the Terminated property to true. So you have to manually keep checking that property and then exit the thread method when it is set to true.
If you might want to terminate a thread then you could be better off spawning another app and killing that if you think its failed - windows will then tidy up after you.

Resources