lundi 2 mai 2016

sequential execution of thread in C++?

I am trying to force sequential execution of threads using condition variable . But its not working . Its coming out as execution time limit exceeds .

#include <iostream>
#include <mutex>
#include <sstream>
#include <thread>
#include <chrono>
#include <condition_variable>
using namespace std;
condition_variable cv;
mutex m;
int i;
bool check_func(int i,int k)
{
    return i == k;
}
void print(int k)
{
   unique_lock<mutex> lk(m);
   int z = k;
   cv.wait(lk,[&]{return check_func(i,z);});            // Line 33
   cout<<"Thread no. "<<this_thread::get_id()<<" parameter "<<k<<"\n";
   i++;
   return;
}
int main() 
{
    thread threads[10];
    for(int i = 0; i < 10; i++)
       threads[i] = thread(print,i);
    for(auto &t : threads)
       t.join();
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire