I'm learning about multithreading in C++11 and I tried this simple test but the output is not what I expected.
#include <thread>
#include <iostream>
#include <mutex>
int main() {
auto function = [](int x) {
std::mutex m;
m.try_lock();
std::cout << "Hello" << x << std::endl;
m.unlock();
return;
};
std::thread t1(function , 1);
std::thread t2(function, 2);
std::thread t3(function, 3);
std::thread t4(function, 4);
t1.join();
t2.join();
t3.join();
t4.join();
std::cin.get();
return 0;
}
I expected the output to be:
Hello1
Hello2
Hello3
Hello4
(maybe not in that order but each hello and number in a separate line)
Instead I got something like this:
HelloHello21
Hello3
Hello4
Or
HelloHello2
1
Hello3
Hello4
What puzzles besides the mutex aparently not locking properly is that it's always the Hello1 the one that gets cut in half.
EDIT: done in VS2015 if it makes any difference (should not because it's all standard?)
Aucun commentaire:
Enregistrer un commentaire