当前位置: 首页>>代码示例>>C++>>正文


C++ mutex::unlock方法代码示例

本文整理汇总了C++中std::mutex::unlock方法的典型用法代码示例。如果您正苦于以下问题:C++ mutex::unlock方法的具体用法?C++ mutex::unlock怎么用?C++ mutex::unlock使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在std::mutex的用法示例。


在下文中一共展示了mutex::unlock方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: thread_function_increase

void thread_function_increase()
{
    for (int i=0; i<3; i++)
    {
        if(g_counter_mutex.try_lock())
            //g_counter_mutex.lock();
        {
            ++g_counter;
            cout << this_thread::get_id() << ": " << i << endl;
            g_counter_mutex.unlock();
            this_thread::sleep_for(std::chrono::seconds(2));
        }
    }
}
开发者ID:guyueguakenan,项目名称:StudyProjects,代码行数:14,代码来源:Mutex.cpp

示例2: usrpGetData

// Thread to import data from the USRP !Size of the arrays in complex -> 2*buffer_size !
void usrpGetData(uhd::rx_streamer::sptr rx_stream, uhd::usrp::multi_usrp::sptr dev, size_t buffer_size, board_60GHz_RX *my_60GHz_RX){
  // Set priority of the thread
  int which = PRIO_PROCESS;
  id_t pid;
  int priority = -20;
  int ret;

  pid = getpid();
  ret = setpriority(which, pid, priority);
  if(ret!=0){  std::cout << "Main priority went wrong in usrpT: " << ret << std::endl ;}

  // Create storage for a single buffer from USRP
  short *buff_short;
  buff_short=new short[2*buffer_size]; 

 
  size_t n_rx_last;
  uhd::rx_metadata_t md;
  //int time=buffer_size/(25)-100; // microsecondes

  while (1){
    n_rx_last=0;

    // Fill buff_short
    while (n_rx_last==0) {
      n_rx_last=rx_stream->recv(&buff_short[0], buffer_size, md, 3.0);
      std::this_thread::yield(); // Avoid active waiting
    };

    // Check if no overflow
    if (n_rx_last!=buffer_size) {
      std::cerr << "I expect the buffer size to be always the same!\n";
      std::cout<<"Read only:"<<n_rx_last<<"\n";
      std::cout<<"Buffer:"<<buffer_size<<"\n";
      //exit(1); 
    }else{

    // Add the just received buffer to the queue
    mtxUsrp.lock();
    usrpQ.push(buff_short);
    mtxUsrp.unlock();
    // Change memory cell used
    buff_short=new short [2*buffer_size];

    // Gives the start to detection part
    sem_post( &usrpReady); 
    }

  }//end while 1
}
开发者ID:tony2909,项目名称:green,代码行数:51,代码来源:rx_60GHz.cpp

示例3: send_logs

void send_logs()
{
  static std::mutex mtx;
  
  mtx.lock();

  Logger::LogPath lp;
  
  const std::map<string, string> logs=
  {
    { lp.errorLogFile, serverLogPath + "/Errors/"},
    { lp.infoLogFile, serverLogPath + "/Info/"},
    { lp.productLogFile, serverLogPath + "/Products/"}
  };
  
  WebClient::FTP ftp;
  
  for (auto itr = logs.begin(); itr != logs.end(); ++itr)
  {
    if (Utils::file_exists(itr->first))
    {
      const string logPath = itr->first + ".copy";
      if (!Utils::copy_paste_file(itr->first, logPath))
	break;
      
      size_t found = itr->first.find_last_of("/\\");
      
      if (found != string::npos)
      {
	const string fileName = itr->first.substr(found+1);
	
	for (int i = 0; i < 2; i++)
	{
	  if (!ftp.upload_file(logPath, itr->second, ftpCredentials, fileName))
	  {
	    cout << "Failed to upload file to ftp server!" << endl;
	    usleep(ONESECOND / 2);
	    continue;
	  }
	  break;
	}  
      }
      else
	cout << "Invalid filepath: " << itr->first << endl;
      
      delete_temp_logs();
    }
  }
  mtx.unlock();
}
开发者ID:Di0n,项目名称:Kassakoppeling,代码行数:50,代码来源:main.cpp

示例4: operator

 void operator() ()
 {
   for (int i = start_; i <= end_; ++i)
     for (int j = 0; j < columns_; ++j)
     {
       char current = matrix_[i][j];
       if ((current >= 'a') && (current <= 'j'))
       {
         mtx.lock();
         ++(*result_)[current - 'a'];
         mtx.unlock();
       }
     }
 }
开发者ID:johann2357,项目名称:threads-cpp,代码行数:14,代码来源:threads_mutex.cpp

示例5: _removeToken

 inline void _removeToken(const std::string& path)
 {
     auto preCheck = m_tokens.find(path);
     if (preCheck != m_tokens.end())
     {
         DeviceToken& tok = *preCheck->second;
         std::shared_ptr<DeviceBase> dev = tok.m_connectedDev;
         tok._deviceClose();
         deviceDisconnected(tok, dev.get());
         m_tokensLock.lock();
         m_tokens.erase(preCheck);
         m_tokensLock.unlock();
     }
 }
开发者ID:dalbano96,项目名称:Vulcan-Space-Robotics-Team,代码行数:14,代码来源:DeviceFinder.hpp

示例6: write

bool FileWriter::write()
{
	mtx.lock();
	while (loadAvail == false)
	{   
		mtx.unlock();
		usleep(100*5);
		mtx.lock();
	}   
	loadAvail = false;
	mtx.unlock();
	if(fs.is_open() && fs.good())
	{
		fs.write(writeBuffer, toWrite);
	}
	mtx.lock();
	loadAvail = true;
	mtx.unlock();

	if (fs.bad())
		return false;
	return true;
}
开发者ID:ChrisZGit,项目名称:HDDRecTool,代码行数:23,代码来源:fileWriter.cpp

示例7: AddToPending

void ImageLoader::AddToPending(const char* Filename)
{
    UploadData New;
    if (Textures.find(Filename) == Textures.end())
    {
        auto d = GetDataForImage(Filename);
        New.Data = d.Data;
        New.Width = d.Width;
        New.Height = d.Height;
        LoadMutex.lock();
        PendingUploads.insert(std::pair<char*, UploadData>((char*)Filename, New));
        LoadMutex.unlock();
    }
}
开发者ID:mechacrash,项目名称:raindrop,代码行数:14,代码来源:ImageLoader.cpp

示例8: dequeue

 bool dequeue(T* data)
 {
     head_mutex.lock();
     
     node* current_head = head;
     node* new_head = current_head->next;
     
     if( new_head == nullptr)
     {
         head_mutex.unlock();
         return false;
     }
     
     *data = new_head->data;
     
     head = new_head; // Swapping dummy-initial node so we avoid to update the tail pointer
                      // Therefore no need for protecting the tail
     
     head_mutex.unlock();
     
     delete current_head; // De allocate previous dummy node
     return true;
 }
开发者ID:IMCG,项目名称:benchmark,代码行数:23,代码来源:queue_mpmc.hpp

示例9: randomCalculate

void randomCalculate(int size, char ch) {
  mutex.lock();  // enter critical section
  for (int i = 0; i < size; ++i) {
    int numerator = rand() % 10;
    int denominator = rand() % 10;
    if (denominator == 0) {
      throw DivisionByZeroException();
    }
    float quotient = static_cast<float>(numerator) / denominator;
    printf(" %c%i/%i=%.2f%c ", ch, numerator, denominator, quotient, ch);
  }
  printf("\n\n");
  mutex.unlock();  // exit critical section
}
开发者ID:duplyakin,项目名称:CppCourse,代码行数:14,代码来源:mutex_1_4.cpp

示例10: show_image

        virtual void show_image() {

            // get the next element inside the CircularBuffer
            cv::Mat frame = input.first.pop();

            if (!frame.empty()) {

                item->setPixmap(QPixmap::fromImage(QImage(frame.data, frame.cols, frame.rows, QImage::Format_RGB888).rgbSwapped()));

            }

            img_view_mutex.unlock();

        }
开发者ID:josiasalexandre,项目名称:smoothPursuit,代码行数:14,代码来源:ImageViewerDevice.hpp

示例11: running

void running(void * aArg) {
	wmra _wmra;

	_wmra.initialize();

	clock_t last_time, current_time;
	last_time = clock()-1;
	current_time = clock();
	double dt;
	int count = 0;

	vector<double> X_dot;
	for (int i = 0; i < 7; i++)
	{
		X_dot.push_back(0.0);
		_wmra.Qarm.push_back(0.0);
	}

	_wmra.sendInputValues(); // zero input

	while (true)
	{
		/****Calculate dt****/
		clock_t current_time = clock();
		dt = (current_time - last_time) / CLOCKS_PER_SEC;
		last_time = current_time;
		/********************/

		/****Data Output (cout)****/
		std::cout.flush();
		std::cout << "\rRunning at " << 1/dt << " seconds per loop" << std::endl;
		std::cout << "Omni Input = [" << _wmra.inputDevice[0] << ", " << _wmra.inputDevice[1] << ", " << _wmra.inputDevice[2] << "]" << std::endl;		
		/********************/

		m.lock(); // mutex locked since using global variable.
		_wmra.sendInputValues(inputValues); 
		m.unlock();

		_wmra.Jacobian_Ground2Endeffector();
		_wmra.weighted_pseudoinverse();
		_wmra.control_joint(_wmra.inputDevice[4], _wmra.inputDevice[5]);
		_wmra.sendInputValues(); // zero input values after they are used

		/**********Updating Devices**********/
		_wmra.ARM.updateArmPosition();
		_wmra.WHEELCHAIR.WMRA_Theta_dot2Xphi_dot();
		_wmra.phi = _wmra.phi + _wmra.WHEELCHAIR.DXphi_dot[1];
		/********************/
	}
}
开发者ID:CARRTUSF,项目名称:WMRAmod,代码行数:50,代码来源:WMRA_module.cpp

示例12: threadfunction_sleep_mutex_try_lock

void threadfunction_sleep_mutex_try_lock(int arg) 
{
  this_thread::sleep_for (std::chrono::milliseconds(200));
  long long count = 0;
  while(true) {
    if(coutLock.try_lock()) {
        cout << "mutex try_lock: " << arg << ", this_thread::get_id=" << this_thread::get_id() << ", tried " << count << " times before we attained the lock" << "\n";
      coutLock.unlock();
      break;
    } else { // lock is busy, do something else.  Let's count the number of times we tried.
      count++;
    }
  }
}
开发者ID:DanBrennan33,项目名称:SenecaOOP345-attic,代码行数:14,代码来源:threading101h.cpp

示例13: request

void GHtttpService::request(GHttpTask* task)
{
    CURL* handle = this->getHandle(task);
    
    mutex.lock();
    this->handle_list.push_back(handle);
    mutex.unlock();
    
    auto success = curl_easy_perform(handle);
    
    mutex.lock();
    long retcode = 0;
    curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE , &retcode);

    if(success == CURLE_OK && retcode == 200)
    {
        task->setStatus(true);
        GLog("http request:%s ok",task->getUrl().c_str());
    }
    else
    {
        GLogE("http request:%s failure",task->getUrl().c_str());
    }
    if(task->getType() == GHTTPTYPE::DOWNLOAD)
    {
        task->closeFile();
        if(task->getAsync())//只有异步时才release
            task->release();
    }
    this->removeHandle(handle);
    mutex.unlock();
    
    if(task->callback)
    {
        task->callback(task->getUrl(),task->getStatus());
    }
}
开发者ID:guang84299,项目名称:cocosfw-cpp,代码行数:37,代码来源:GHtttpService.cpp

示例14: main

int main() {
    // Это вектор потоков.
    std::vector<std::thread> threads;


    // Запускаем все наши потоки
    for (int i = 0; i < threadsNumber; ++i) {
        threads.push_back(std::thread(threadFunc, i));
    }


    // Этот блок кладёт задания в нашу очередь.
    unsigned i = 1;
    while (i++ < 10000) {

        // Сгенерируем два случайных числа.
        std::random_device rd;   // non-deterministic generator
        std::mt19937 gen(rd());
        long long k =  static_cast<long long>(abs(gen())) % 102;
        long long k1 =  static_cast<long long>(abs(gen())) % 102;

        // Сунем эти два числа в блокирующую очередь.
        writeMutex.lock();
        std::cout << "k == " << k  << " given " << std::endl;
        std::cout << "k1 == " << k1  << " given " << std::endl;
        writeMutex.unlock();

        ourQueue.enqueue(k);
        ourQueue.enqueue(k1);
    }
/*
    // Запускаем все наши потоки
    for (int i = 0; i < threadsNumber; ++i) {
        threads.push_back(std::thread(threadFunc, i));
    }
*/
    // Бросим ядовитые пилюли, чтобы убить потоки.
    for (int i = 0; i < threadsNumber; ++i)
        ourQueue.enqueue(-1);


    // Ждём пока все потоки завершатся.
    for (int j = 0; j < threadsNumber; ++j) {
        if (threads[j].joinable())
            threads[j].join();
    }

    return 0;
}
开发者ID:feezboom,项目名称:MIPT_OOP_2th_sem,代码行数:49,代码来源:main.cpp

示例15: func

void func(size_t thread_index, tree_mutex *m)
{
	size_t n = 10000;
	//dbg(thread_index, n);
	while (n--)
	{
		m->lock(thread_index);
		assert(m2.try_lock());
		++i;
		++ai;
		++ai2;
		m2.unlock();
		m->unlock(thread_index);
	}
}
开发者ID:dima74,项目名称:Seminars,代码行数:15,代码来源:tree_mutex.cpp


注:本文中的std::mutex::unlock方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。