multithreading,c++11 , When the main exits where does the console output go?


When the main exits where does the console output go?

Question:

Tag: multithreading,c++11
#include<iostream>
#include<thread>
using namespace std;
void func()
{
    for (int i = 0; i < 10000; i++)cout << "Print" << endl;
}

int main()
{
    thread t(func);
    t.detach();
    cout << "Exit" << endl;
    return 0;
}

In the above code, when the main exits, where does the "Print"text would be gone,since it doesn't have an output stream? Is there any dummy stream for inserting data which has no use?


Answer:

When main exits it calls exit which terminates all threads, regardless detached or not. This is because exit terminates the entire process.

The C++ runtime runs main as exit(main(argc, argv)), so that returning from main causes exit to be called.

You can terminate your main thread, if you wish, by calling pthread_exit. In this case the main thread will not return from main and will not call exit. The application will keep running until some other thread calls exit or all threads terminate (or the application crashes). This is how it works on Linux, not sure about Windows.

std::cout object and the other standard streams are available at least until exit is called. These streams are initialized using Schwarz Counter idiom, which makes sure they get initialized before its first use and destroyed after the last user is gone. In other words, if you have a global object with a constructor and destructor, which gets initialized before main is entered and destroyed after (when exit is called), that standard stream is still going to be available in that global object destructor. Basically, there is a reference counter associated with each standard stream, each translation unit (object file) increments this reference counter on the startup and decrements on termination.

ISO/IEC 14882:2011(E) says:

27.4 Standard iostream objects

27.4.1.2 The objects [the standard streams] are constructed and the associations are established at some time prior to or during the first time an object of class ios_base::Init is constructed, and in any case before the body of main begins execution†. The objects are not destroyed during program execution. The results of including in a translation unit shall be as if defined an instance of ios_base::Init with static storage duration. Similarly, the entire program shall behave as if there were at least one instance of ios_base::Init with static storage duration.

Constructors and destructors for static objects can access these objects to read input from stdin or write output to stdout or stderr.


Related:


C++ operator []


c++,c++11,operator-overloading
I am trying to implement the operator [] that is to be used once for Set and once as Get, i need to differentiate between the two cases, as in the case of get, i need to throw an exception if the returned value is equal to -1; whereas in...

What happens if all node.js's worker threads are busy


javascript,node.js,multithreading
I try to understand how node.js works and although I have read this article: When is the thread pool used? I am not sure what happens if all worker threads are busy and another async I/O operation is ready to be executed. If I got this http://www.future-processing.pl/blog/on-problems-with-threads-in-node-js/ article right, the...

How does the kernel separate threads from processes


linux,multithreading,linux-kernel
Suppose I have a browser process like Firefox, that has pid = 123. Firefox has 5 opened tabs each running in a separate thread, so in total it has 5 threads. So I want to know in depth, how the kernel will separate the process into the thread to execute...

Set Label From Thread


vb.net,multithreading,winforms
Form1.vb Imports System.Threading Public Class Form1 Dim demoThread As Thread Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim Start As New Class1 Me.demoThread = New Thread( _ New ThreadStart(AddressOf Start.ThreadProcSafe)) Me.demoThread.Start() End Sub Delegate Sub SetTextCallback([text] As String) Public Sub SetText(ByVal [text] As String) ' InvokeRequired required...

C++11 Allocation Requirement on Strings


c++,string,c++11,memory,standards
I had heard that C++11 was going to require strings to be allocated in contiguous memory. I even thought I saw a stack overflow question on it, but I can't seem to find it. I know that in practice both gcc and Visual Studio do allocate strings contiguously, I'm just...

How to re-write templated function to handle type deduction


c++,templates,c++11
So, I have this search function for the map container: template <typename Key, typename T> void searchInMapByKey(std::map<Key,T> Map, T keyValue) { if(Map.empty()) { std::cout << "Map is empty, nothing to search for..." << "\n"; } else { for(const auto & element : Map) { if(element.first==keyValue) { std::cout << keyValue <<...

Calling dispatch_sync from a concurrent queue - does it block entirely?


ios,objective-c,multithreading,swift,grand-central-dispatch
Let's say I hypothetically call a dispatch_sync from a concurrent queue - does it block the entire queue or just that thread of execution?

No match for 'operator*' error


c++,c++11
Hello fellow programmers! I was going to write a small program for calculating total pay for different periods of time depending on the amount of hours and the salary that the user enters. I managed to make a small bit of the program but when I try to run it...

Web API - Set each thread with the HttpRequestMessage id?


c#,.net,multithreading,task-parallel-library,web-api
I have a web api coded in c#. The web api uses functionality which is shared with other in-house components. it depends on single threaded flows and uses thread local storage to store objects, and session information. Please don't say if it's good or bad, that's what I have to...

C++ why does SFINAE fail with only a class template parameter?


c++,templates,c++11,sfinae
I'm using SFINAE in the style of this answer in order to call a generic vector object by using an appropriate member function. For example, the following code calls operator[](int) const first, and if that doesn't exist then operator()(int) const: template<int I> struct rank : rank<I-1> { static_assert(I > 0,...

Does wait() need synchronization on local variable


java,multithreading,synchronization
I had this code (which was working fine): public static void runOnUiThread(Activity c, final Runnable action) { // Check if we are on the UI Thread if (Looper.getMainLooper() == Looper.myLooper()) { // If we are, execute immediately action.run(); return; } // Else run the runnable on the UI Thread and...

Is executing C++ code in comments with certain Unicode characters allowed, like in Java?


c++,c++11,unicode,comments
I know that executing Java code in comments with certain Unicode characters is allowed. Please see this question for further clarification Executing Java code in comments. So was just curious to know if C++ has such features?

How can we make a thread to sleep for a infinite time in java?


java,multithreading,thread-sleep
Pls help me to understand how can we make a thread to sleep for a infinite time period .

wait for an event regulary


multithreading,events
In a program I need to wait for an event (keypress) and get it's char. after that program will continue. this progress will Repeat several time. in my first try, codes run and any character did not save. I find out I should use threading but I am not Familiar...

Any way to catch an exception occurring on a thread I don't own?


c#,multithreading,exception
I'm using a crappy third party library because unfortunately I have no choice. This library creates a bunch of threads internally when I call it, and occasionally throws a NullReferenceException on one of these threads. Is there any way for me to catch these exceptions even though I don't own...

In c++11 what should happen first: raw string expansion or macros?


c++,c++11,preprocessor,rawstring
This code works in visual c++ 2013 but not in gcc/clang: #if 0 R"foo( #else int dostuff () { return 23; } // )foo"; #endif dostuff(); Visual C++ removes the if 0 first. Clang expands the R raw string first (and never defining dostuff). Who is right and why?...

Should checking loop conditions be counted towards total number of comparisons?


c++,algorithm,sorting,c++11
I have implemented three different sorting algorithms and now I want to confirm that my approach of counting the total number of comparisons is correct. In my mind, the number of comparisons shouldn't be tied to the conditional branches because if the condition isn't met, the comparison was still made...

Images not appearing on WPF form when loading asynchronously


c#,wpf,multithreading,listbox,backgroundworker
I'm attempting to display (in a ListBox with a custom DataTemplate) a series of BitmapSource frames (thumbnails) extracted from a multi-page tiff image. When I process the tiff on the UI thread, and either directly add the images to a listbox's item collection or add them to a bound ObservableCollection,...

“Emulating” std::declval issues. Works (kind of) in g++, fails to compile in clang++


c++,c++11,decltype
Trying to better understand std::declval, I came up with the following "toy model" code: #include <iostream> #include <typeinfo> struct Bar { Bar(double); // some non-default ctor double f(); // some function of which return type we want to get }; using Barref = Bar&&; // emulating std::declval<Bar>() int main() {...

Why is initialization of enum class temporaries with arbitrary values allowed?


c++,c++11
I came across some code like the following in one the CppCon 2014 talks that confused the heck out of me. The audience accepted it without comment, so I presume that it's legal: enum class Foo { Bar }; Foo const v1 = Foo(5); The question is: why does this...

Multiple Threads searching on same folder at same time


c#,multithreading,file-search
Currently I have a .txt file of about 170,000 jpg file names and I read them all into a List (fileNames). I want to search ONE folder (this folder has sub-folders) to check if each file in fileNames exists in this folder and if it does, copy it to a...

Call template function for the value of a pointer out of a template function, in C++


c++,templates,pointers,c++11
I am trying to call a template function for the pointer that was given as template parameter in my calling function. My code is: template <> struct serialize_helper<std::string> { // not important code... } }; template <class T> inline void serializer(const T& obj, StreamType::iterator& res) { if(std::is_pointer<T>::value) { //THIS doesn'...

Passing something as this argument discards qualifiers


c++,c++11
Using the below code, i get the following compile error: In static member function ‘static std::string ctedata::Record::getDispatcher<std::basic_string<char> >::impl(const ctedata::Record&, const string&)’: /home/jason/CrownTheEmpire/lib/ctedata/data.h:111:38: error: passing ‘const std::map<std::basic_string<char>, std::basic_string<char> >’ as ‘this’ argument discards qualifiers [-fpermissive] return rec.fieldValues_[field]; ^ In file included from /usr/include/c++/5.1.0/map:61:0, from...

std::condition_variable – notify once but wait thread wakened twice


c++,multithreading
Here's a simple C++ thread pool implementation. It's an altered version orginated from https://github.com/progschj/ThreadPool. #ifndef __THREAD_POOL_H__ #define __THREAD_POOL_H__ #include <vector> #include <queue> #include <memory> #include <thread> #include <chrono> #include <mutex> #include <condition_variable> #include <future> #include <functional> #include <stdexcept> namespace ThreadPool { class FixedThreadPool { public: FixedThreadPool(size_t); template<class F, class......

Why is the boolean value within a structure within a vector not being updated?


c++,c++11
This might sound like a very basic question, but I have trying to fix a simple bug for over an hour now and I can't seem to understand what's happening. I have the following structure declaration in my header file: struct StudentBody { string name; Vec2 position; bool disabled; StudentBody(string...

java multithreading start() and run() [duplicate]


java,multithreading
This question already has an answer here: Java: What's the difference between Thread start() and Runnable run() 10 answers Below is my Multithreading class: public class Multithreading extends Thread{ public void run(){ for(int i=1;i<5;i++){ try{ Thread.sleep(500); }catch(InterruptedException e){ System.out.println(e); } System.out.println(i); } } public static void main(String args[]) {...

Same function with and without template


c++,c++11
I am trying to understand a piece of code of C++11. A class contains 2 functions as shown below: class abc { public: void integerA(int x); template<typename typ> void integerA(typ x); }; I am unable to understand benefit of declaring 2 same functions. Why not declare only one template function?...

Type function that returns a tuple of chosen types


c++,templates,c++11,metaprogramming
I've implemented a type function Tuple that turn a list of My_enum values into an std::tuple of corresponding types: #include <tuple> enum My_enum{ t_int, t_double }; // Bind_type is a type function that given a My_enum returns the corresponding type template<My_enum E> struct Bind_type; template<> struct Bind_type<t_int>{ using type =...

How can I simulate a nested function without lambda expressions in C++11?


c++,function,c++11,lambda,allegro
I have the following code: int main(int argc, char **argv) { App app(800, 600); app.add_event_scene(Scene("Event Plot", event_plot)); Image x("sample.png"); struct foo { static void visual_plot() { x.draw(); } }; // Error. app.add_visual_scene(Scene("Visual Plot", foo::visual_plot)); app.run(); return 0; } And I get the following error: ||=== Build: Debug in Joy-Plus-Plus (compiler:...

Is there standard implementation for thread block/resume in java SE?


java,multithreading,wait
I need to block execution of a thread until resumed from another thread. So I wrote my own implementation using wait() method. Which seems to be working, but it is far from simple. Is there any ready to use solution? Preferably in java SE 6? Or do I have to...

How can I convert an int to a string in C++11 without using to_string or stoi?


c++,string,c++11,gcc
I know it sounds stupid, but I'm using MinGW32 on Windows7, and "to_string was not declared in this scope." It's an actual GCC Bug, and I've followed these instructions and they did not work. So, how can I convert an int to a string in C++11 without using to_string or...

Sorting vector of Pointers of Custom Class


c++,sorting,c++11,vector
I have vector<FPGA*> current_generation_, which I'd like to sort by FPGA member fitness_ using the sort_members function. Applicable code follows: bool sort_members (FPGA* fpga_first, FPGA* fpga_second) { return (fpga_first->fitness() < fpga_second->fitness()); }; fpga.hpp #include <vector> class FPGA { public: explicit FPGA(int input_gates, int output_gates, int normal_gates); const int fitness(); protected:...

Dereferencing a temporary unique_ptr


c++,c++11,unique-ptr
unique_ptr<A> myFun() { unique_ptr<A> pa(new A()); return pa; } const A& rA = *myFun(); This code compiles but rA contains garbage. Can someone explain to me why is this code invalid? Note: if I assign the return of myFun to a named unique_ptr variable before dereferencing it, it works fine....

Crystal convert the idea behind Thread pool to Fibers/spawn


multithreading,coroutine,crystal-lang
I'm having some hard time learning the idea behind Fibers\coroutines and the implementation in Crystal. I hope this is the right place to ask this, I'll totally accept a "not here" answer :) This is my usual way of handling multi-threading in Ruby: threads = [] max_threads = 10 loop...

EXC_BAD_ACCESS error occurring when running recursive merge sort method in a thread


c++,multithreading,sorting,recursion
I'm having trouble with my C++ code in xCode. I've tried debugging and I can't fix it. I know it's roughly when my mergeSort() method calls my mergeNumbers() method. I know it's not the method itself because I've run the method without threading and it works just fine. It's when...

Can't compile C++11 source using GCC 5.1 toolchain


c++,c++11,gcc5
I'm trying to compile a library written with C++11 features using GCC 5.1 on Ubuntu. However, it complains std::unique_ptr is not defined. gcc (Ubuntu 5.1.0-0ubuntu11~14.04.1) 5.1.0 g++ (Ubuntu 5.1.0-0ubuntu11~14.04.1) 5.1.0 CXX flags: -std=c++11 -Wall -Wextra -Weffc++ -pedantic Output: error: ‘unique_ptr’ in namespace ‘std’ does not name a template type std::unique_ptr<...

Invoke form showdialog is not modal


vb.net,multithreading,invoke
I have 2 forms, 1 MainForm and 1 Form2. I am trying to display Form2 as a modal form and background from MainForm. Here's what I have so far. The default MainForm appears and after 5 seconds it will show Form2 as a Modal form from a background thread. I...

Implicit use of initializer_list


c++,c++11,initializer-list
§[dcl.init.list] 8.5.4/2: The template std::initializer_list is not predefined; if the header <initializer_list> is not included prior to a use of std::initializer_list — even an implicit use in which the type is not named (7.1.6.4) — the program is ill-formed. Does that mean this program is ill-formed? #include <vector> int main()...

Java how to limit number of threads acting on method


java,multithreading,memory-management
I have java method in my web application doing heavy file operation. The thing is, if more than 5 threads come simultaneously (which will come in testing phase) it breaks down. I mean it cannot handle heavy traffic. That's why I want to handle maximum 5 requests at a time...

std::move on a C++ class does not move all members?


c++,c++11,move
I understand that using v.push_back(std::move(foo)) will move foo contents to a vector. However I do not understand why the below code : #include <iostream> #include <vector> struct Foo { std::string s; float f; friend std::ostream& operator<<(std::ostream& stream,const Foo& foo) { stream << "{" << foo.s << ":" << foo.f <<...

Looking to pause a thread using thread.sleep


java,multithreading
I am using a mouse listener for mouse pressed and released. When the mouse is pressed I want to have a counter incrementing a variable, and when the mouse is released I want to decrement that variable. Right now, my code is working and does that but the increment is...

Can you call dispatch_sync from a concurrent thread to itself without deadlocking?


ios,objective-c,multithreading,swift,grand-central-dispatch
I know you would deadlock by doing this on a serial queue, but I haven't found anything that mentions deadlocking by doing it on a concurrent queue. I just wanted to verify it wont deadlock (it doesn't seem like it would, as it would only block one of the threads...

C++ error: deduced conflicting types for parameter 'T' string vs const char *


c++,string,templates,c++11,char
So, I am writing a simple, templated search function for deque container. Here's the code: template <typename T> void searchInDequeFor(std::deque<T> Deque, T searchValue) { for(const auto & element : Deque) { if(Deque.empty()) { std::cout << "Deque is empty, nothing to search for..." << "\n"; } else if(element==searchValue) { std::cout <<...

Calling variadic template function with no args failing


c++,c++11
Given the following code: #include <iostream> template <typename... Args> void foo(Args&&... bargs, Args&&... aargs) { std::cout << "Hello" << std::endl; } int main() { foo<int, double>(1, 2.0, 3, 4.0); //OK foo<char>('c', 'd'); // OK foo(); //FAIL } I get the following compiler error: In function 'int main()': 15:9: error: no...

Call to implicitly-deleted copy constructor in LLVM(Porting code from windows to mac)


c++,osx,c++11,compiler-errors,llvm
We are in the process of porting some c++ code from windows to mac and are having issues compiling it with LLVM 6.1 using c++11. We are encountering errors all over the place of "Call to implicitly-deleted copy contructor" Some of these errors are popping up in our code. for...

Java 5 Multi threading, catch thread exceptions


java,multithreading,exception,concurrency,java-5
I've got a class that generates threads (file i/o). I need to catch exceptions in the thread - I don't want to do anything fancy, I want to kill the main thread, rather, stop processing altogether so it can start over. If I catch the exceptions in the thread, that's...

How can I know the lock information in java?


java,multithreading,locking
Is there any tool or way that can get all the information about the locks in java? for example, if there is a java program, it creates two threads, and both threads require locks for some variable. Is there any tools that can output the information like which thread locks...

Atomic/not-atomic mix, any guarantees?


c++,multithreading,c++11,atomic
Let's I have GUI thread with code like this: std::vector<int> vec; std::atomic<bool> data_ready{false}; std::thread th([&data_ready, &vec]() { //we get data vec.push_back(something); data_ready = true; }); draw_progress_dialog(); while (!data_ready) { process_not_user_events(); sleep_a_little(); } //is it here safe to use vec? As you see I not protect "vec" by any kind of...

performance issues executing list of stored procedures


c#,multithreading,performance,loops
I'm having some performance issues when starting my windows service, the first round my lstSps is long (about 130 stored procedures). Is there anyway to speed this up (except for speeding the stored procedures up)? When the foreach is over and goes over to the second round it goes faster,...