Loga
Loga

Reputation: 45

Should threads created inside main and threads created inside functions behave differently?

I'm new to programming/C++ and I'm experimenting with simple multithreading. I have tried the following codes:

Example 1

#include <iostream>
#include <thread>         

void printFunc() {        
    while(1) {        
        std::cout << "threadOne Running..." << std::endl;           
    }
}        

int main() {
    std::thread threadOne(printFunc);            
    threadOne.detach();         

    while(1) {        
        std::cout << "main running..." << std::endl;        
    }
    return 0;
}

Example 2

#include <iostream>
#include <thread>         

void printFunc() {        
    while(1) {        
        std::cout << "threadOne running..." << std::endl;            
    }
}        

void initThread() {        
    std::thread threadOne(printFunc);            
    threadOne.detach();         
}         

int main() {        
    initThread();
    while(1) {        
        std::cout << "main running..." << std::endl;        
    }
    return 0;
}

When I run example 1 using Visual Studio in debug & release mode, it prints "main running..." most of the time and prints "threadOne running..." once in a while. But when I run example 2, it prints both of them (jumps between two prints "equally").

Edit:
Execution of example 1
Screenshot of execution of example 1

Execution of example 2

Screenshot of execution of example 2

Upvotes: 3

Views: 185

Answers (1)

Ol1v3r
Ol1v3r

Reputation: 788

Possible reason for what you're seeing;

Because you did not specify which version of C++ you're using, I'll assume its C++11; As per Is cout thread-safe

Concurrent access to a synchronized (§27.5.3.4) standard iostream object’s formatted and unformatted input (§27.7.2.1) and output (§27.7.3.1) functions or a standard C stream by multiple threads shall not result in a data race (§1.10). [ Note: Users must still synchronize concurrent use of these objects and streams by multiple threads if they wish to avoid interleaved characters. — end note ]

Meaning that you still have to synchronize both cout streams. One way of doing that would be to wrap cout in your own class and assign it a mutex.

Upvotes: 2

Related Questions