线程互斥锁解锁顺序

时间:2015-04-04 15:40:22

标签: c++ multithreading c++11 mutex

请考虑以下代码:

#include <iostream> 
#include <mutex> 
#include <thread> 
#include <vector> 
#include <chrono>
using namespace std; 
const int SIZE = 10;

mutex myMutex;
std::vector<int> strange;

void add_to_vector(int i) { 
   lock_guard<mutex> g(myMutex);

   if (strange.size() < 100) {
       cout << "Dodaje do bazy" << i << std::endl;
       strange.push_back(i);
       cout << "Dodałem do bazy" << i << std::endl;
   }

} 
void f(int n) { 
    while (strange.size() < 100)
    {
    add_to_vector(n);
    std::this_thread::sleep_for(std::chrono::microseconds(100));
}
} 
 int main()
 {
     thread t1(f, 1); // 0-9 
     thread t2(f, 2); // 10-19 
     thread t3(f, 3); // 20-29 
     thread t4(f, 4); // 30-39 
     thread t5(f, 5); // 40-49 

     t1.join();
     t2.join();
     t3.join();
     t4.join();
     t5.join();

     for (auto a : strange) {
         std::cout << a << ", ";
     }
     return 0;
 }

线程是否正在等待互斥锁解锁,排队?似乎解锁后,对资源的访问获得了一个随机的线程。如何确保他们以FIFO顺序访问资源线程?

0 个答案:

没有答案