c++ - Execution not switching between thread (c++11) -


i beginner in c++11 multithreading. working small codes , came problem. here code:

#include <iostream> #include <thread> #include <vector> #include <mutex>  std::mutex print_mutex;  void function1() {     std::cout << "thread1 started" << std::endl;      while (true)     {         std::unique_lock<std::mutex> lock(print_mutex);         (size_t = 0; i<= 1000000000; i++)             continue;         std::cout << "this function1" << std::endl;         lock.unlock();     } }  void function2() {     std::cout << "thread2 started" << std::endl;     while (true)     {         std::unique_lock<std::mutex> lock(print_mutex);         (size_t = 0; <= 1000000000; i++)             continue;         std::cout << "this function2" << std::endl;         lock.unlock();     } }  int main() {     std::thread t1(function1);     std::thread t2(function2);      t1.join();     t2.join();      return 0; } 

i have written code intuition of expecting following output:

thread1 started
thread2 started

function1
function2
function1
. .
.
.

but output shown follows:

thread1 started
thread2 started

this function1

function1
function1
.
.
.

where going wrong?

both of thread doing following steps:

  • lock
  • long empty loop
  • print
  • unlock
  • lock
  • long empty loop
  • (and on)

practically, haven't left any time context switching, there lock right after unlock. solution: swap "lock" , "long empty loop" steps, "print" step locked, scheduler can switch other thread during "long empty loop".

welcome threads!

edit: pro tipp: debugging multithreading programs hard. it's worth insert plain printf() indicate locks , unlocks (the right order: lock, printf , printf unlock), when program seems correct. in case see 0 gap between unlock-lock.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -