How to use simple threading in C++

2 Answers

0 votes
#include <iostream>
#include <string>
#include <thread>

// The function we execute on the new thread
void task1(std::string str) {
    std::cout << "task1: " << str << "\n";
}

int main()
{
    // Constructs the new thread and runs it
    std::thread t1(task1, "C++ 1");
    
    // Not blocking execution
    std::cout << "main() 1\n";
    std::cout << "main() 2\n";
    std::cout << "main() 3\n";
    std::cout << "main() 4\n";
    
    std::thread t2(task1, "C++ 2");
    std::thread t3(task1, "C++ 3");
    
    t1.join();
    t3.join();
    t2.join();
}


  
/*
run:
 
main() 1
main() 2
main() 3
main() 4
task1: C++ 1
task1: C++ 2
task1: C++ 3
  
*/

 



answered Mar 22, 2025 by avibootz
0 votes
#include <iostream>
#include <string>
#include <thread>

// The function we execute on the new thread
void task1(std::string str) {
    std::cout << "task1: " << str << "\n";
}

int main()
{
    // Constructs the new thread and runs it
    std::thread t1(task1, "C++ 1");
    
    // Not blocking execution
    std::cout << "main() 1\n";
    std::cout << "main() 2\n";
    
    std::thread t2(task1, "C++ 2");
    
    std::cout << "main() 3\n";
    
    std::thread t3(task1, "C++ 3");
    
    std::cout << "main() 4\n";
    
    t1.join();
    t3.join();
    t2.join();
    
    std::cout << "main() 5\n";
}


  
/*
run:
 
main() 1
main() 2
task1: C++ 1
main() 3
task1: C++ 2
main() 4
task1: C++ 3
main() 5

*/

 



answered Mar 22, 2025 by avibootz

Related questions

2 answers 218 views
218 views asked Jan 20, 2017 by avibootz
1 answer 155 views
155 views asked Apr 28, 2017 by avibootz
1 answer 197 views
1 answer 168 views
1 answer 158 views
...