void run() {
        while (1) {

            unique_lock<mutex> sqlLock(sqlMutex);
            cout << this_thread::get_id() << ": waiting until sqlQueue is NOT empty " << sqlQueue.size() << endl;
            sqlCond.wait(sqlLock, []{ return !sqlQueue.empty(); } );
            string sql = sqlQueue.front();
            sqlQueue.pop();
            sqlLock.unlock();

            cout << this_thread::get_id() << ": working on sql=" << sql << endl;
            string res = "";
            if (0 != exec(sql, res)) {
                cout << this_thread::get_id() << ": failed with error=" << m_error << endl;
                res = "failed with error="+m_error;
            }
            
            unique_lock<mutex> resultLock(resultMutex);
            cout << this_thread::get_id() << ": setting result to resultQueue, now size=" << resultQueue.size() << endl;
            resultQueue.emplace(res);
            resultLock.unlock();
            resultCond.notify_one();

        }
    }
Beispiel #2
0
void conn_get(tcp::iostream *&stream) {
#if USE_CONN_POOL
    {
        unique_lock<mutex> lock(_conn_mutex);
        while (_conns.size() == 0 && _n_conn_alloc >= CONN_MAX) {
            _conn_avail_cv.wait(lock);
        }

        if (_conns.size() > 0) {
            stream = _conns.back();
            _conns.pop_back();
        } else if (_n_conn_alloc < CONN_MAX) {
            ++ _n_conn_alloc;
            stream = new tcp::iostream();
            lock.unlock();
            stream->connect("127.0.0.1", "1481");
        }
    }
#else
    _conn_mutex.lock();
    if (_fb_conn == NULL) {
        _fb_conn = new tcp::iostream();
        _fb_conn->connect("127.0.0.1", "1481");
    }
    stream = _fb_conn;
#endif    
}
Beispiel #3
0
int main() {
	
		thread t1(erzeuger1);
		thread t2(erzeuger2);
		thread t3(verbraucher);
		thread t4(watcher);
	
	unique_lock<mutex> sperre2(m);
		cout << "\n";
		condivar.notify_one();
		condivar.wait(sperre2);

		

		//t1.detach();		mit detach wird der thread asugeführt ohen berücksichtigung der anderer Threads


		t1.join();
		t2.join();		//mit join() wird gewartet
		t3.join();
		t4.join();
		
		system("PAUSE");
	
	
}
Beispiel #4
0
void worker( void )
{
    while( true ){
        int data;
        {
            // unique_lockではコンストラクタでロックを取得し、デストラクタでロックを解除する。
            // また、明示的にロック、アンロックが可能である。
            unique_lock<mutex> lk(queue_mutex);
            // キューにデータがない場合はキューにデータが追加されたことが
            // 通知されるまで待つ。CPUを余分に消費することがない。
            while( v_queue.empty() ){
                // waitを呼ぶ前にはlkがロック状態でなければならない。
                // C++11でもspurious wakeupの問題があることに注意。
                // ここでready_cond.notify_one()が呼ばれるまでブロックする。
                // ready_cond.notify_one()が呼ばれると、再びロックを取得した状態で、この関数から抜ける。
                ready_cond.wait(lk);
            }
            //
            data = v_queue.front();
            v_queue.pop();
        }
        lock_guard<mutex> l(print_mutex);
        printf( "%p %d\n", this_thread::get_id(), data );
        fflush( stdout );
    }
}
void work(int serial, int &value, condition_variable &c, mutex &m, int &turn)
{
    while (1) {
        {
            unique_lock w{m};
            // ожидаем наступления события turn == serial
            c.wait(w, [&turn, &serial]() { return turn == serial; });
        }

        if (value >= 1000) {
            lock_guard w{m};
            turn = (turn + 1) % 2;
            c.notify_all();
            break;
        }
        cout << serial <<  " " << value << endl;
        ++value;

        {
            lock_guard w{m};
            turn = (turn + 1) % 2;
            c.notify_all();
        }
    }
}
    void WriteLock() {
        unique_lock<mutex> lk(mtx);
        writerQ.wait(lk, [this] { return !(is_writing || readers > 0); } );
        is_writing = true;

        lk.unlock();
    }
Beispiel #7
0
	static void filter()
	{
		size_t filterCount = 0;
	
		for (;;) {
			unique_lock<mutex> filterLock(sync);

			step2Condition.wait(filterLock, []() {return !nums.empty() || count == NUM_COUNT; });
			if (nums.empty()) {
				break;
			}

			int front = nums.front();
			if (front % 3 != 0 && front % 13 != 0) {
				filteredNums.push_back(front);
				filterCount++;
			}
			nums.erase(nums.begin(), nums.begin() + 1);

			filterLock.unlock();
		}
		step3Condition.notify_all();

		// Print trace of consumption
		//lock_guard<mutex> out(print);
		//cout << "Step 2 thread done -- filtered: " << filterCount << endl;
	}
Beispiel #8
0
	static void output(size_t remainderBase)
	{
		// Create out file
		ofstream outF("output" + to_string(remainderBase) + ".txt");

		size_t outputCount = 0;

		for (;;) {

			// Get lock for sync mutex; Wait for step 2
			unique_lock<mutex> outputLock(sync);
			if (filteredNums.empty()) break;
			step3Condition.wait(outputLock, []() {return !filteredNums.empty(); });
			if (filteredNums.empty()) break;

			// Get modulus
			if (!filteredNums.empty() && filteredNums[0] % FILE_FILTER_COUNT == remainderBase) {
				// Write to file
				outputCount++;
				outF << filteredNums[0] << endl;
				filteredNums.erase(filteredNums.begin(), filteredNums.begin() + 1);
			}

			outputLock.unlock();
		}

		// print stuff
		lock_guard<mutex> out(print);
		cout << "Group " << remainderBase << " has " << outputCount << " numbers" << endl;
	}
Beispiel #9
0
bool EnterStepping(std::function<void()> callback) {
	lock_guard guard(pauseLock);
	if (coreState != CORE_RUNNING && coreState != CORE_NEXTFRAME) {
		// Shutting down, don't try to step.
		return false;
	}
	if (!gpuDebug) {
		return false;
	}

	gpuDebug->NotifySteppingEnter();

	// Just to be sure.
	if (pauseAction == PAUSE_CONTINUE) {
		pauseAction = PAUSE_BREAK;
	}
	isStepping = true;

	callback();

	do {
		RunPauseAction();
		pauseWait.wait(pauseLock);
	} while (pauseAction != PAUSE_CONTINUE);

	gpuDebug->NotifySteppingExit();
	isStepping = false;
	return true;
}
Beispiel #10
0
void pub_func(const po::variables_map vm) {
	context_t ctxt(1);
	socket_t pub(ctxt, ZMQ_PUB);
	zmq_socket_monitor(pub, "inproc://monitor.pub", ZMQ_EVENT_ALL);
	thread monitor_thread(monitor_func, ref(ctxt), "inproc://monitor.pub", "pub", ref(pubDoneFlag));
	std::string payload(vm["size"].as<size_t>(), '.');
	if (vm.count("no-linger")) {
		int linger = 0;
		pub.setsockopt(ZMQ_LINGER, &linger, sizeof(linger));
	}
	if (vm.count("sndhwm")) {
		auto sndhwm = vm["sndhwm"].as<int>();
		pub.setsockopt(ZMQ_SNDHWM, &sndhwm, sizeof(sndhwm));
	}
	pub.bind("tcp://*:4404");
	{
		unique_lock<mutex> lock(subReadyMutex);
		while(subReadyFlag == false)
			subReadyCond.wait(lock);
	}
	for(size_t pubCount=0; pubCount<vm["count"].as<size_t>(); ++pubCount) {
		for(size_t partNo=1; partNo<vm["parts"].as<size_t>(); ++partNo)
			assert(pub.send(payload.data(), payload.size(), ZMQ_SNDMORE)==payload.size());
		assert(pub.send(payload.data(), payload.size())==payload.size());
	}
	this_thread::sleep_for(chrono::seconds(vm["recovery-time"].as<long>()));
	for(size_t pubCount=0; pubCount<vm["recovery-count"].as<size_t>(); ++pubCount) {
		if (vm["recovery-rate"].as<size_t>() > 0)
			this_thread::sleep_for(chrono::milliseconds(1000/vm["recovery-rate"].as<size_t>()));
		pub.send("bye", 3);
	}
	pubDoneFlag = true;
	monitor_thread.join();
}
Beispiel #11
0
void showID(int ID)
{
    unique_lock<mutex> lck(mtx);
	while (!ready) cv.wait(lck);
	// 3 2 1 GO!
	scout<<"Thread #"<<ID<<endl;
}
    //! Dequeues log record from the queue, blocks if no log records are ready to be processed
    bool dequeue_ready(record_view& rec)
    {
        unique_lock< mutex_type > lock(m_mutex);
        while (!m_interruption_requested)
        {
            if (!m_queue.empty())
            {
                const boost::log::aux::timestamp now = boost::log::aux::get_timestamp();
                enqueued_record const& elem = m_queue.top();
                const uint64_t difference = (now - elem.m_timestamp).milliseconds();
                if (difference >= m_ordering_window)
                {
                    // We got a new element
                    rec = elem.m_record;
                    m_queue.pop();
                    return true;
                }
                else
                {
                    // Wait until the element becomes ready to be processed
                    m_cond.timed_wait(lock, posix_time::milliseconds(m_ordering_window - difference));
                }
            }
            else
            {
                // Wait for an element to come
                m_cond.wait(lock);
            }
        }
        m_interruption_requested = false;

        return false;
    }
Beispiel #13
0
 void pop(T &result)
 {
     unique_lock<mutex> u(m);
     c.wait(u, [&] {return !q.empty();} );
     result = move_if_noexcept(q.front());
     q.pop();
 }
		vector<T> get_all() {
			unique_lock<mutex> l(cv_m);
			cv.wait(l, [this](){return count(this->v.begin(), this->v.end(), T()) == 0;});
			vector<T> ret = v;
			fill(v.begin(), v.end(), T());
			return ret;
		}
		T get(size_t k) {
			unique_lock<mutex> l(cv_m);
			cv.wait(l, [this, k](){return this->v[k] != T();});
			T t = v[k];
			v[k] = (T)0;
			return t;
		}
Beispiel #16
0
    void run_thread()
    {
        unique_lock<mutex> guard(m_lock);

        DBClientBase *client = new_connection();

        while(true) {
            if(!client->isStillConnected()) {
                m_log->error() << "A thread lost its connection, reconnecting..." << endl;
                delete client;
                client = new_connection();
            }

            if(m_operation_queue.size() > 0) {
                DBOperation *op = m_operation_queue.front();
                m_operation_queue.pop();

                guard.unlock();
                handle_operation(client, op);
                guard.lock();
            } else if(m_shutdown) {
                break;
            } else {
                m_cv.wait(guard);
            }
        }

        delete client;
    }
	void acquire(){
		unique_lock<mutex> lck(mtx);
		while(count == 0){
			cv.wait(lck);
		}
		count--;
	}
Beispiel #18
0
 void push(int data) {
     {
         unique_lock<mutex> lk(m);
         cv.wait(lk,[this](){ return data_queue.size()<max_size; });
         data_queue.push(data);
     }
     cv.notify_all();
 }
void thread_func2(mutex & mtx, condition_variable & cv)
{
    std::cout << "thread_func2: begin" << std::endl;
    mutex::scoped_lock lc(mtx);
    cv.wait(lc);
    std::cout << "thread_func2: get lock" << std::endl;
    std::cout << "thread_func2: end" << std::endl;
}
Beispiel #20
0
    T pop () {
      lock lock (list_mutex);
      while (list.empty ()) {
	m_condition.wait (lock);
      }
      T retval = list.front ();
      list.pop_front ();
      return retval;
    }
Beispiel #21
0
 void pop(int& data) {
     {
         unique_lock<mutex> lk(m);
         cv.wait(lk,[this](){ return data_queue.size()>0; });
         data = data_queue.front();
         data_queue.pop();
     }
     cv.notify_all();
 }
Beispiel #22
0
void InputDevice::StopPolling() {
	inputThreadEnabled = false;

	lock_guard guard(inputMutex);
	if (inputThreadStatus) {
		inputEndCond.wait(inputMutex);
	}
	delete inputThread;
	inputThread = NULL;
}
void movePeople(vector<Human> &v) {
	unique_lock<mutex> lck(mtx);
	while (index == v.size()) cv.wait(lck);
	current_floor = v[index].current_floor;
	cout << " Elevator is picking up person:  " << v[index].getID() << " at floor " << current_floor << endl;
	current_floor = v[index].next_floor;
	cout << " Elevator has dropped off person: " << v[index].getID() << " at floor " << current_floor << endl;
	index++;
	cv.notify_all();
}
Beispiel #24
0
    void signal(int id)
    {
        unique_lock<mutex> lk(mx);

        std::cout << "signaling " << id << "\n";

        signaled_id = id;
        cv.notify_all();

        cv.wait(lk, [&] { return signaled_id == -1; });
    }
Beispiel #25
0
void even_thread() 
{ 
    while (ctrEven < MAX_ELEMS) { 
        unique_lock<mutex> lk(mut); 
        cond.wait(lk, [] { return ((ctrOdd - ctrEven) == 3); }); 
        ctrEven += 2; 
        cout << ctrEven << endl; 
        cond.notify_one(); 
        lk.unlock(); 
    } 
}
Beispiel #26
0
    void run()
    {

        {
            mutex::guard g( mutex_ );
            ++worker_count_;

            if ( worker_count_ == active_workers_ )
            {
                manager_cv_.notify_one();
            }
        }

        shared_ptr< runnable > task;

        for ( bool active = true; active; )
        {
            {
                mutex::guard g( mutex_ );

                while ( worker_count_ <= active_workers_ && tasks_.empty() )
                {
                    ++idle_workers_;
                    workers_cv_.wait( g );
                    --idle_workers_;
                }

                if ( worker_count_ <= active_workers_ ||
                     ( state_ == STOPPING && tasks_.size() ) )
                {
                    if ( tasks_.size() )
                    {
                        task = tasks_.front();
                        tasks_.pop_front();
                    }
                }
                else
                {
                    --worker_count_;
                    if ( worker_count_ == active_workers_ )
                    {
                        manager_cv_.notify_one();
                    }
                    return;
                }
            }

            if ( task )
            {
                task->execute();
                task.reset();
            }
        }
    }
void print_number_worker(int num) {
	while(counter < 50) {

		unique_lock<mutex> lk(m);
		cv.wait(lk, [] { return can_print; });

		cout << num << endl;
		counter++;
		cv.notify_one();
	}
}
Beispiel #28
0
 T& pop()
 {
     unique_lock<mutex> uniqueLock(mtx);
     /* block thread if queue is empty */
     while (tsQueue.empty()) {
         cv.wait(uniqueLock);
     }
     auto& entry = tsQueue.front();
     tsQueue.pop();
     return entry;
 }
Beispiel #29
0
// Thread function: Condition waiter
void ThreadCondition2(void * aArg)
{
  cout << " Wating..." << flush;
  lock_guard<mutex> lock(gMutex);
  while(gCount > 0)
  {
    cout << "." << flush;
    gCond.wait(gMutex);
  }
  cout << "." << endl;
}
Beispiel #30
0
    void acquire_read() const
    {
        mutex::guard g( mutex_ );

        while ( has_writer_ || writer_waiting_ )
        {
            reader_cv_.wait( mutex_ );
        }

        ++reader_count_;
    }