How to delete pthreads? - c++

I want use 5 threads on C++ program. I want create new thread when old ends working. How to implement it? How delete old threads?
Thanks!

You can use pthread_join for this purpose:
The pthread_join() function shall suspend execution of the calling
thread until the target thread terminates, unless the target thread
has already terminated. On return from a successful pthread_join()
call with a non-NULL value_ptr argument, the value passed to
pthread_exit() by the terminating thread shall be made available in
the location referenced by value_ptr. When a pthread_join() returns
successfully, the target thread has been terminated. The results of
multiple simultaneous calls to pthread_join() specifying the same
target thread are undefined. If the thread calling pthread_join() is
canceled, then the target thread shall not be detached.

You can do something of this sort,
In main, create 5 threads (detached ones possibly).
When a thread is about to terminate create a new detached thread
(and use a variable protected by a lock which indicates number of threads running
currently, if its less than 5 create thread else exit) within the
thread before exiting.
That way you will continuously create new threads.
Detached threads run detached from other threads(main included), no one waits for them to complete their execution (They don't make a thread to stop executing). Whereas, when you use pthread_join(threadName,NULL) the thread calling this function has to wait until threadName has terminated. [Both, pthread_detach and pthread_join ensure the threads resources are released]
There is nothing like deleting pthreads.
Something this way,
static int count = 5;
pthread_mutex_t mutexForCount = PTHREAD_MUTEX_INITIALIZER;
pthread_attr_t attr;
void* tFn(void* arg)
{
std::cout<<"\nI am "<<pthread_self();
pthread_mutex_lock(&mutexForCount);
count--;
if(count<=5)
{
pthread_t temp;
pthread_create(&temp,&attr,tFn,NULL);
count++;
}
pthread_mutex_unlock(&mutexForCount);
}
int main()
{
pthread_t threadArray[5];
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
for(int i = 0;i<5;i++)
{
pthread_create(&threadArray[i],NULL,tFn,NULL);
}
for(int i = 0;i<5;i++)
{
pthread_join(threadArray[i],NULL);
}
pthread_exit(NULL);
}
Note: The attribute and the mutex variables should be destroyed at the end of the program. I have assumed this program runs continuosly.

The thread ends when the thread function exits.

Related

Std thread detach

Having this simple example:
#include <iostream> // std::cout
#include <thread> // std::thread, std::this_thread::sleep_for
#include <chrono> // std::chrono::seconds
void new_thread(int n) {
std::this_thread::sleep_for(std::chrono::seconds(n));
std::cout << "New thread - exiting!\n";
}
int main() {
std::thread (new_thread, 5).detach();
std::cout << "Main thread - exiting!\n";
return 0;
}
Is it possible for the new_thread not to be automatically terminated by the main thread and to do it's work - outputs New thread - exiting! after 5 secs?
I'm NOT mean the case of join when the main thread waits for a child, but for the main thread to detach the spawned thread and terminates leaving the new thread doing it's work?
Calling detach on a thread means that you don't care about what the thread does any more. If that thread doesn't finish executing before the program ends (when main returns), then you won't see its effects.
However, if the calling thread is around long enough for the detached thread to complete, then you will see the output. Demo.
[basic.start.main]/5 A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit with the return value as the argument. If control flows off the end of the compound-statement of main, the effect is equivalent to a return with operand 0.
[support.start.term]/9
[[noreturn]] void exit(int status);
Effects:
...
Finally, control is returned to the host environment.
You seem to expect that when main returns, the program waits for all threads to finish - in effect, implicitly joins all detached threads. That's not what happens - instead, the program terminates, and the operating system cleans up resources allocated to the process (including any threads).
detach separates your thread from the main thread. You want to use join()
Separates the thread of execution from the thread object, allowing
execution to continue independently. Any allocated resources will be
freed once the thread exits.
After calling detach *this no longer owns any thread.
From ref

Use same boost:thread variable to create multiple threads

In the following example(not all the code included just the necessary portions):
class A
{
public:
void FlushToDisk(char* pData, unsigned int uiSize)
{
char* pTmp = new char[uiSize];
memcpy(pTmp, pData, uiSize);
m_Thread = boost::thread(&CSimSwcFastsimExporter::WriteToDisk, this, pTmp, uiSize);
}
void WriteToDisk(char* pData, unsigned int uiSize)
{
m_Mtx.lock();
m_ExportFile.write(pData, uiSize);
delete[] pData;
m_Mtx.unlock();
}
boost::thread m_Thread;
boost::mutex m_Mtx
}
is it safe to use the m_Thread that way since the FlushToDisk method can be called while the created thread is executing the WriteToDisk method.
Or should I do something like:
m_Thread.join();
m_Thread = boost::thread(&CSimSwcFastsimExporter::WriteToDisk, this, pTmp, uiSize);
Would this second solution be slower than the first?
From what i saw at http://www.boost.org/doc/libs/1_59_0/doc/html/thread/thread_management.html#thread.thread_management.tutorial
"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".
So in my case the threads should not be interrupted or?
Thanks in advance.
The second solution will pause the main thread to wait until the writer thread completes. You would be able to remove mutex if you go this way. You are guaranteed to have one file writing thread.
The first solution is going to allow main thread to continue, and will create an uncontrolled writing thread - serialized on the mutex. While you might believe this is better (main thread will not wait) I do not like this solution for several reasons.
First, you do not have any control over the number of created threads. If the function is called often, and the operation is slow, you can easily run out of threads! Second, and much more important, you will accumulate a backlog of detached threads waiting on mutex. If your main application decides to exit, all those threads will be silently killed and the updates will be lost.

thread access shared variables after main thread exit

What would happen in a multi-thread C++ program if a detached thread accesses shared variables(e.g. global variable) after the call thread exits and destruct the shared variable?
class A {
public:
A() { printf("Constructing A\n"); }
~A() { printf("Destructing A\n"); }
void printSomething() { printf("A is printing\n"); }
}
A a;
void thread_func() {
printf("begin thread.\n");
sleep(3); // make sure main thread exit first
a.printSomething();
printf("ending thread");
}
int main(int argc, char** argv) {
std::thread t(thread_func);
t.detach();
return 0;
}
The program produces:
bash$ ./a.out
Constructing A
Destructing A
bash$
It seems main thread created global variable a and destroy it when exiting. Then what would happen after 3 seconds if the detached child thread tries to access this global variable?
And another confusion is, why does main thread clear up all resources when it exits? Looks like the lifetime of global variable is only dependent on main thread?
Processes exit when main() returns, or any thread calls exit() or _exit().
However, main() can call pthread_exit() - and that will not terminate the process. Per the Linux pthread_exit() man page:
When a thread terminates, process-shared resources (e.g., mutexes,
condition variables, semaphores, and file descriptors) are not
released, and functions registered using atexit(3) are not called.
After the last thread in a process terminates, the process terminates
as by calling exit(3) with an exit status of zero; thus,
process-shared resources are released and functions registered using
atexit(3) are called.
Threads do not have their own memory per-se, but share memory with their parent process. They are tied to their parent; therefore, whenever the parent dies, it's child threads are also killed off.

Calling pthread_cancel on a join'ed thread causes segfault under linux

The following code ends with a segmentation fault on the first call to pthread_cancel but only under linux. Under Mac OS it runs fine. Am I not allowed to call pthread_cancel on a thread that has finished running? Maybe I should not call pthread_cancel at all?
#include <iostream>
#include <pthread.h>
using namespace std;
void* run(void *args) {
cerr << "Hallo, Running" << endl;
}
int main() {
int n = 100;
pthread_t* pool = new pthread_t[n];
for(int i=0;i<n;i++) {
pthread_t tmp;
pthread_create(&tmp,NULL,&run,NULL);
pool[i] = (tmp);
}
for(int i=0;i<n;i++) {
pthread_join(pool[i],0);
}
for(int i=0;i<n;i++) {
pthread_cancel(pool[i]);
}
}
See POSIX XSH 2.9.2:
Although implementations may have thread IDs that are unique in a system, applications should only assume that thread IDs are usable and unique within a single process. The effect of calling any of the functions defined in this volume of POSIX.1-2008 and passing as an argument the thread ID of a thread from another process is unspecified. The lifetime of a thread ID ends after the thread terminates if it was created with the detachstate attribute set to PTHREAD_CREATE_DETACHED or if pthread_detach() or pthread_join() has been called for that thread. A conforming implementation is free to reuse a thread ID after its lifetime has ended. If an application attempts to use a thread ID whose lifetime has ended, the behavior is undefined.
If a thread is detached, its thread ID is invalid for use as an argument in a call to pthread_detach() or pthread_join().
You may not use a pthread_t after the thread it refers to has been joined, or if the thread has terminated while detached. Simply remove the pthread_cancel code from your program. It's wrong. pthread_cancel is for cancelling an in-progress thread, and has very tricky requirements for using it safely without causing resource leaks. It's not useful for threads which exit on their own.

pthread - How to start running a new thread without calling join?

I want to start a new thread from the main thread. I can't use join since I don't want to wait for the thread to exit and than resume execution.
Basically what I need is something like pthread_start(...), can't find it though.
Edit:
As all of the answers suggested create_thread should start thread the problem is that in the simple code below it doesn't work. The output of the program below is "main thread". It seems like the sub thread never executed. Any idea where I'm wrong?
compiled and run on Fedora 14 GCC version 4.5.1
void *thread_proc(void* x)
{
printf ("sub thread.\n");
pthread_exit(NULL);
}
int main()
{
pthread_t t1;
int res = pthread_create(&t1, NULL, thread_proc, NULL);
if (res)
{
printf ("error %d\n", res);
}
printf("main thread\n");
return 0;
}
The function to start the thread is pthread_create, not
pthread_join. You only use pthread_join when you are ready to wait,
and resynchronize, and if you detach the thread, there's no need to use
it at all. You can also join from a different thread.
Before exiting (either by calling exit or by returning from main),
you have to ensure that no other thread is running. One way (but not
the only) to do this is by joining with all of the threads you've
created.
the behaviour of your code depends on the scheduler; probably the main program exits before printf in the created thread has been executed. I hope simple sleep(some_seconds) at the end of the main() will cause the thread output to appear :)
the join call waits for the thread to terminate and exit.
if you want your main thread to continue its execution while the child thread is executing, don't call join: the child thread will execute concurrently with the main thread...
Just create the thread with the detached attribute set to on. To achieve this, you can either call pthread_detach after the thread has been created or pthread_attr_setdetachstate prior to its creation.
When a thread is detached, the parent thread does not have to wait for it and cannot fetch its return value.
you need to call pthread_exit in the end of man(), which will cause main to wait other thread to start and exit.
Or you can explicitly call pthread_join to wait the newly created thread
Otherwise, when main returns, the process is killed and all thread it create will be killed.
The thread starts automatically when you create it.
Don't you just need to call pthread_create?
static void *thread_body(void *argument) { /* ... */ }
int main(void) {
pthread_t thread;
pthread_create(&thread, NULL, thread_body, NULL);
/* ... */