#include <iostream>
#include <thread>
#include <mutex>
std::mutex mx;
void some_function()
{
while(1)
{
std::lock_guard<std::mutex> mx_guard(mx);
std::cout << "some_function()\n";
}
}
void some_other_function()
{
while(1)
{
std::lock_guard<std::mutex> mx_guard(mx);
std::cout << "some_other_function\n";
}
}
int main()
{
std::thread t1(some_function);
std::thread t2 = std::move(t1); //t2 will be joined
t1 = std::thread(some_other_function);
if(t2.joinable())
{
std::cout << "t2 is joinable()\n";
t2.join(); //calling join for t1
}
if(t1.joinable())
{
std::cout << "t1 is joinable()\n";
t1.join();
}
return 0;
}
У меня есть другой выход для этой программы на windows и linux. В окнах с использованием visual studio 13 компилятора я получаю следующий вывод.C++ 11 Поведение различного поведения на linux и windows
some_function()
some_other_function
some_function()
some_other_function
some_function()
some_other_function
some_function()
some_other_function
some_function()
some_other_function
some_function()
some_other_function
Но на Linux с помощью GCC на выходе отличается
some_function()
some_function()
some_function()
some_function()
some_function()
some_function()
some_function()
some_other_function
some_other_function
some_other_function
some_other_function
some_other_function
some_other_function
some_other_function
На окнах два потока печатают один за другим, но на Linux это не то же самое поведение. Использование мьютекса на linux не синхронизируется. Как синхронизировать на linux?
Сколько у вас ЦП в вашей системе? Заказ выполнения между потоками не гарантируется. – myaut
«Использование мьютекса на Linux не синхронизируется» - вы не можете заключить, что из этого вывода. Вообще. – Mat
Что вы * точно * планируете делать? Мы не можем вам помочь, если все, что вы предоставляете, является шаблоном. –