Why does my thread not run in background? - c++

In the listing bellow, I expect that as I call t.detach() right after the line when the thread is created, the thread t will run in background while the printf("quit the main function now \n") will called and thenmain will exit.
#include <thread>
#include <iostream>
void hello3(int* i)
{
for (int j = 0; j < 100; j++)
{
*i = *i + 1;
printf("From new thread %d \n", *i);
fflush(stdout);
}
char c = getchar();
}
int main()
{
int i;
i = 0;
std::thread t(hello3, &i);
t.detach();
printf("quit the main function now \n");
fflush(stdout);
return 0;
}
However from what it prints out on the screen it is not the case. It prints
From new thread 1
From new thread 2
....
From new thread 99
quit the main function now.
It looks like the main function waits until the thread finishes before it executes the commandprintf("quit the main function now \n"); and exits.
Can you please explain why it is? What I am missing here?

The problem is that your thread is too fast.
It's able to print all 100 strings before main gets a chance to continue.
Try making the thread slower and you'll see the main printf before that of the thread.

It happens, based on your OS scheduling. Moreover the speed of your thread affects the output too. If you stall the thread (change 100 to 500 for example), you will see the message first.
I just executed the code and the "quit the main function now." message appeared first, like this:
quit the main function now
From new thread 1
From new thread 2
From new thread 3
From new thread 4
...
You are right about detach:
Detaches the thread represented by the object from the calling thread, allowing them to execute independently from each other.
but this does not guarantee that the message "quit the main function now" will appear first, although it's very likely.

It looks like the main function waits until the thread finishes before it executes the command printf("quit the main function now \n"); and exits.
That's because when you create a thread, it gets scheduled for execution, but the order of events across threads is no longer sequential, ordered, or deterministic. In some runs of your program, the output of hello3 will occur before quit the main function now, in some runs it'll print afterwards, and in some runs, the output will be interleaved. This is a form of Undefined Behavior normally referred to as a "Race Condition". In most (but not all) cases, the output of hello3 prints last because there's some overhead (varies by the OS and processor) in setting up a thread, so the several microseconds it takes to properly build the thread and ready it for execution takes so long that the printf statement in your main function already had time to execute and flush before the thread was ready to run.
If you want explicit evidence that things are running concurrently, you should add more work into the main thread before the quit statement so that it becomes unlikely that the main function will finish before the thread is ready to start executing.

There are two major problems with your code:
As soon the main function exits, you will have undefined behaviour because the variable i, referenced by the detached thread, no longer exists.
As soon the whole process ends after the main function returns, the detached thread will also die.

Related

std::thread created as detach thread terminates when main exits [duplicate]

This question already has answers here:
How does thread::detach() work in C++11?
(2 answers)
What happens to a detached thread when main() exits?
(7 answers)
Closed 1 year ago.
I am writing the following c++ code to create a detach thread :
void threadF() {
ofstream f("data") ;
for(int i=1; i<=5; i++) {
f<<"t1:::"<<i<<"\n" ;
f.flush() ;
sleep(1) ;
}
f.close() ;
}
int main() {
thread t1(threadF) ;
cout<<"main #1\n" ;
sleep(2) ;
t1.detach() ;
cout<<"main #2\n" ;
}
When I run this code, I have the following observations :
main exits after 2 secs (as expected)
the detach child thread also seems to be running only for 2secs because the output data file contains only 2 lines.
I expected that the thread should have executed completely and that the output data file should have contained 5 lines. This is not happening
I need an explanation for this behavior.
AS per the ink What happens to a detached thread when main() exits?, does it mean that the detached thread would automatically terminate when the main exits ?
I need an explanation for this behavior.
When main returns, the process is terminated. If there was a thread running, there are no guarantees that it will have a chance to finish.
Furthermore, technically touching any global state after main has returned results in undefined behaviour because all static storage objects will be destroyed by the main thread.
Basically, std::thread::detach is rarely useful because you simply have to use some other way to join the thread instead. There's no standard way to "wait for all detached threads and then stop". There are platform specific ways though (pthread_exit).

new thread causes issues c++

I have a void function that has a while (true) loop inside of it, and both Sleep(); and std::this_thread::sleep_for(std::chrono::milliseconds()); do nothing. And yes, I am aware I'm sleeping by millisecond and not seconds, by multi-threading I mean I have done:
std::thread nThread(Void);
nThread.detach();
When I just call the method, this issue doesn't occur, and it sleeps just fine.
Essentially what I'm doing:
#include <stdio.h>
#include <thread>
void thisisVoid()
{
while (true)
{
printf("Print");
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
int main()
{
std::thread nThread(thisisVoid);
nThread.detach();
}
It's not the sleep that's the problem. You haven't really asked a question, but I think what you're saying is that if you don't detach, you get a crash.
Here's why...
C++ doesn't like you to exit the program with dangling threads. You can either detach them or join them. There's a startup time with your new thread, and if you just exit main at the bottom, your first thread probably hasn't run yet. And it hasn't been allowed to clean up because you haven't joined against it or detached it.
So you have to do one or the other in main(). If you join against it you'll wait until it's done. If you detach it, you could exit before he's even executed.

C++ threads inside a 'for' loop print wrong values

I'm trying to understand multithreading in C++, but I’m stuck in this problem: if I launch threads in a for loop they print wrong values. This is the code:
#include <iostream>
#include <list>
#include <thread>
void print_id(int id){
printf("Hello from thread %d\n", id);
}
int main() {
int n=5;
std::list<std::thread> threads={};
for(int i=0; i<n; i++ ){
threads.emplace_back(std::thread([&](){ print_id(i); }));
}
for(auto& t: threads){
t.join();
}
return 0;
}
I was expecting to get printed the values 0,1,2,3,4 but I often got the same value twice. This is the output:
Hello from thread 2
Hello from thread 3
Hello from thread 3
Hello from thread 4
Hello from thread 5
What am I missing?
The [&] syntax is causing i to be captured by reference. So quite often therefore i will be further advanced when the thread runs than you might expect. More seriously, the behaviour of your code is undefined if i goes out of scope before a thread runs.
Capturing i by value - i.e. std::thread([i](){ print_id(i); }) is the fix.
Two problems:
You have no control over when the thread runs, which means the value of the variable i in the lambda might not be what you expect.
The variable i is local for the loop and the loop only. If the loop finishes before one or more thread runs, those threads will have an invalid reference to a variable whose lifetime have ended.
You can solve both these problems very simply by capturing the variable i by value instead of by reference. That means each thread will have a copy of the value, and that copy will be made uniquely for each thread.
Another thing:
Do not wait until to have always an ordered sequence: 0, 1, 2, 3, ... because the multithreading execution mode has a specificity: indeterminism.
Indeterminism means that the execution of the same program, under the same conditions, gives a different result.
This is due to the fact that the OS schedules threads differently from one execution to another depending on several parameters: CPU load, priority of other processes, possible system interruptions, etc.
Your example contains only five threads, so it's simple. Try to increase the number of threads, and for example put a sleep in the processing function. You will see that the result can be different from one execution to another.

Thread ending unexpectedly. c++

I'm trying to get a hold on pthreads. I see some people also have unexpected pthread behavior, but none of the questions seemed to be answered.
The following piece of code should create two threads, one which relies on the other. I read that each thread will create variables within their stack (can't be shared between threads) and using a global pointer is a way to have threads share a value. One thread should print it's current iteration, while another thread sleeps for 10 seconds. Ultimately one would expect 10 iterations. Using break points, it seems the script just dies at
while (*pointham != "cheese"){
It could also be I'm not properly utilizing code blocks debug functionality. Any pointers (har har har) would be helpful.
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
#include <string>
using namespace std;
string hamburger = "null";
string * pointham = &hamburger;
void *wait(void *)
{
int i {0};
while (*pointham != "cheese"){
sleep (1);
i++;
cout << "Waiting on that cheese " << i;
}
pthread_exit(NULL);
}
void *cheese(void *)
{
cout << "Bout to sleep then get that cheese";
sleep (10);
*pointham = "cheese";
pthread_exit(NULL);
}
int main()
{
pthread_t threads[2];
pthread_create(&threads[0], NULL, cheese, NULL);
pthread_create(&threads[1], NULL, wait, NULL);
return 0;
}
The problem is that you start your threads, then exit the process (thereby killing your threads). You have to wait for your threads to exit, preferably with the pthread_join function.
If you don't want to have to join all your threads, you can call pthread_exit() in the main thread instead of returning from main().
But note the BUGS section from the manpage:
Currently, there are limitations in the kernel implementation logic for
wait(2)ing on a stopped thread group with a dead thread group leader.
This can manifest in problems such as a locked terminal if a stop sig‐
nal is sent to a foreground process whose thread group leader has
already called pthread_exit().
According to this tutorial:
If main() finishes before the threads it has created, and exits with pthread_exit(), the other threads will continue to execute. Otherwise, they will be automatically terminated when main() finishes.
So, you shouldn't end the main function with the statement return 0;. But you should use pthread_exit(NULL); instead.
If this doesn't work with you, you may need to learn about joining threads here.

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);
/* ... */