What happens when a thread is constructed, and how is the thread executed - c++

I'm completely new to multithreading and have a little trouble understanding how multithreading actually works.
Let's consider the following example of code. The program simply takes file names as input and counts the number of lowercase letters in them.
#include <iostream>
#include <thread>
#include <mutex>
#include <memory>
#include <vector>
#include <string>
#include <fstream>
#include <ctype.h>
class LowercaseCounter{
public:
LowercaseCounter() :
total_count(0)
{}
void count_lowercase_letters(const std::string& filename)
{
int count = 0;
std::ifstream fin(filename);
char a;
while (fin >> a)
{
if (islower(a))
{
std::lock_guard<std::mutex> guard(m);
++total_count;
}
}
}
void print_num() const
{
std::lock_guard<std::mutex> guard(m);
std::cout << total_count << std::endl;
}
private:
int total_count;
mutable std::mutex m;
};
int main(){
std::vector<std::unique_ptr<std::thread>> threads;
LowercaseCounter counter;
std::string line;
while (std::cin >> line)
{
if (line == "exit")
break;
else if (line == "print")
counter.print_num(); //I think that this should print 0 every time it's called.
else
threads.emplace_back(new std::thread(&LowercaseCounter::count_lowercase_letters, counter, line));
}
for (auto& thread : threads)
thread->join();
}
Firstly I though that the output of counter.print_num() will print 0 as far as the threads are not 'joined' yet to execute the functions. However, It turns out that the program works correctly and the output of counter.print_num() is not 0. So I asked myself the following questions.
What actually happens when a thread is constructed?
If the program above works fine, then thread must be executed when is created, then what does std::thread::join method do?
If the thread is executed at the time of creation, then what's the point of using multithreading in this example?
Thanks in advance.

You seem to be under the impression that the program can only be running one thread at a time, and that it needs to interrupt whatever it's doing in order to execute the code of the thread. That's not the case.
You can think of a thread as a completely separate program that happens to share memory and resources with the program that created it. The function you pass as an argument is that program's 'main()` for every intent and purpose. In Linux, threads are literally separate processes, but as far as C++ is concerned, that's just an implementation detail.
So, in a modern operating system with preemptive multitasking, much like multiple programs can run at the same time, threads can also run at the same time. Note that I say can, it's up to the compiler and OS to decide when to give CPU time to each thread.
then what does std::thread::join method do?
It just waits until the thread is done.
So what would happen if I didn't call join() method for each one of threads
It would crash upon reaching the end of main() because attempting to exit the program without joining a non-detached thread is considered an error.

As you said, in c++ the thread is executed when it is created all std::thread::join does is wait for the thread to finish execution.
In your code all the threads will start executing simultaneously in the loop and then the main thread will wait for each thread to finish execution in the next loop.

Related

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.

Resource deallocation for Detach thread in C++

I was going through this post on stack overflow in which the accepted answer says:
what happens to a detached thread when main() exits is:
It continues running (because the standard doesn't say it is stopped), and that's well-defined, as long as it touches neither (automatic|thread_local) variables of other threads nor static objects.
While in this post the accepted answer says that:
Process terminates when main() exits, and all threads are killed.
To see the behavior, I tested below code on g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4 which suggests that once the main thread exit other detach thread also exit.
#include <iostream>
#include <thread>
#include <unistd.h>
#include <fstream>
using namespace std;
void foo()
{
std::cout<<"Inside foo\n";
int i=0;
ofstream myfile;
while(i<10)
{
std::cout<<"Inside while\n";
myfile.open ("/home/abc/example.txt",ios::app);
myfile << "Writing this to a file.\n";
myfile.close();
i++;
sleep(1);
}}
int main()
{
std::thread first (foo);
first.detach();
sleep(5);
return 0;
}
So why in many posts here on stack overflow suggests that detach thread continues running in background even if main thread exit? In what condition the detach thread continues to run in background when main exit and which one of the above statement is true?
Thanks in advance.
The standard defines the scope of thread as being the program:
1.10/1: A thread of execution (also known as a thread) is a single flow of control within a program (...) The execution of the entire program consists of an execution of all of its threads.
The standard says about detached threads:
30.3.3/1: A thread of execution is detached when no thread object represents that thread.
So there's nothing in the standard that suggests hat a thread could survive its program.
If you want to keep something running in background after the end of the program, you have to fork or create a separate process that will run in the background with its own resources and threads.

Asynchronous IO in C++11

I need to run some iterative algorithm of which I don't know whether it will converge to the desired accuracy within reasonable time. It would therefore be cool if I could print the residual after each iteration and once I'm satisfied/out of patience I could tell the program to write the current solution to disk and terminate.
Usually, to achieve this the program would have to ask after every iteration whether it should terminate now, and most of the time I would have to tell it not to. This is clearly annoying. Can't I tell the program to run until I hit a certain key, and once I do it should finish the current iteration, write the approximation to disk and terminate?
Yes, you can, and you can even do it using only standard C++11 features. The trick is to spawn a new thread whose only job it is to listen to std::cin. Once the user writes anything, the listening thread sets a flag which tells the worker thread to abort. In the following small example, I implement a "stopwatch" using this technique.
#include <iostream>
#include <thread>
#include <atomic>
int main() {
std::atomic<bool> abort(false);
std::thread t([&abort] () {
std::cout << "Abort?";
std::cin.peek();
abort = true;
});
unsigned long i = 0;
while (!abort) ++i;
t.join();
std::cout << "Counted to " << i << std::endl;
return 0;
}
You may now try to terminate the program exactly when it reached 100000000. :-)

Running a periodic loop in background in C++/C

I'm trying to create C++ program in the sense of embedded hardware programs that work in real time. The main loop in my C++ program uses a delay time of 250milliseconds. It's like:
int main()
{
do{
doSomething();
delay(250);
}while(1)
}
The delay in main loop is crucial for my program to operate.
I need to check something else using 5ms delays.
sideJob()
{
while(1){
checkSomething();
delay(5);
}
}
How do I define the function sideJob to run at the same with the main loop. All in all, I need to get the hang of threading by using, if possible, simple functions. I'm using Linux. Any help will be greately appreaciated.
EDIT: This is what I got so far, But I want to run the sideJob and main thread at the same time.
#include <string>
#include <iostream>
#include <thread>
using namespace std;
//The function we want to make the thread run.
void task1(string msg)
{
cout << "sideJob Running " << msg;
}
int main()
{
// Constructs the new thread and runs it. Does not block execution.
thread t1(task1, "Hello");
//Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
t1.join();
while(1){
printf("Continuous Job\n");
}
}
Use different threads in order to do this tasks in parallel.
To learn for more about this, look here.
For an example on StackOverflow, look here.
You can also find plenty of tutorials out there (for example, here).

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.