I am a beginner in C++11 multithreading. I am working with small codes and came into this problem. Here is the 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);
for(size_t i=0;i<=1000000000;i++)
continue;
std::cout << "This is function1" << std::endl;
lock.unlock();
}
}
void function2()
{
std::cout << "Thread2 started" << std::endl;
while(true)
{
std::unique_lock<std::mutex> lock(print_mutex);
for(size_t i=0;i<=1000000000;i++)
continue;
std::cout << "This is 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 with the intuition of expecting the following output:
Thread1 started
Thread2 started
This is function1
This is function2
This is function1
. .
.
.
But the output shown is as follows:
Thread1 started
Thread2 startedThis is function1
This is function1
This is function1
.
.
.
Where am I going wrong?
Aucun commentaire:
Enregistrer un commentaire