Threads
Sometimes we need to control and protect some critical sections in the code as the following program illustrates.
Control Access
File: thread3.cpp
#include <iostream> #include <thread> using namespace std ; void thread_function1() { for( int i1=0 ; i1<5 ; i1++ ) cout << "Thread function1: " << i1 << endl ; } void thread_function2() { for( int i1=0 ; i1<5 ; i1++ ) cout << "Thread function2: " << i1 << endl ; } int main() { thread t1( &thread_function1 ); // t1 starts running thread t2( &thread_function2 ); // t2 starts running //cout << "main thread\n"; // main thread waits for the thread t1 to finish t1.join(); t2.join(); return 0; } Output: $ rm a.exe ; g++ thread3.cpp ; ./a.exe Thread function1: Thread function2: 00 Thread function1: Thread function2: 11 Thread function1: Thread function2: 22 Thread function1: Thread function2: 33 Thread function1: Thread function2: 44 We notice that the output from the 2 threads is intermingled. Let's correct this issue by making sure that only one thread executes a "cout" at a time.