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


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

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


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

示例1: playUnicastSong

/*******************************************************************
** Function: playUnicastSong()
**
** Date: 
**
** Revisions:
**
**
** Designer: Rhea Lauzon
**
** Programmer: Rhea Lauzon
**
** Interface:
**			bool playUnicastSong(string songName)
**				string songName -- requested song for unicast
**
** Returns:
** bool -- false on failure for libvlc, true on success

** Notes: Plays a unicast song for a specific client.
**  
*******************************************************************/
bool playUnicastSong(string songName)
{
	libvlc_media_player_t *unicastMediaPlayer;
	libvlc_media_t *unicastSong;

	int index = 0;
	char memoryOptions[256];
	sprintf_s(memoryOptions, VLC_OPTIONS, (long long int)(intptr_t)(void*) &handleUnicastStream, (long long int)(intptr_t)(void*) &prepareUnicastRender);
	const char* const vlcArgs[] = { "-I", "dummy", "--verbose=0", "--sout", memoryOptions};
	
	 //create an instance of libvlc
	if ((unicastInst = libvlc_new(sizeof(vlcArgs) / sizeof(vlcArgs[0]), vlcArgs)) == NULL)
	{
		cerr << "Failed to create libvlc instance." << endl;
		return false;
	}

	string song_to_play(song_dir + "/" + songName);
	unicastSong = libvlc_media_new_path(unicastInst, song_to_play.c_str());

	//load the song
	if (unicastSong == NULL)
	{
		cerr << "failed to load the song." << endl;
		return false;
	}

	//lock the mutex while another client has it
	songMutex.lock();

		
	//create a media player
	unicastMediaPlayer = libvlc_media_player_new_from_media(unicastSong);


	//Begin playing the music
	libvlc_media_release(unicastSong);

	//starts the process of streaming the audio (calls pre-render then handleStream)
	libvlc_media_player_play(unicastMediaPlayer);

	while (!libvlc_media_player_is_playing(unicastMediaPlayer))
	{
	// Wait for the song to start
	}

	//sleep constantly till the song finishes
	while (!uniDone && libvlc_media_player_is_playing(unicastMediaPlayer))
	{
		Sleep(1000);
	}

	libvlc_media_player_release(unicastMediaPlayer);

	//remove the finished client from the deque
	waitingClients.pop_front();

	//send a message to the client saying the unicast is over
	songMutex.unlock();


	return true;
}
开发者ID:MrChimick,项目名称:Comm-Audio,代码行数:85,代码来源:unicast.cpp

示例2: move

		TxHandle::TxHandle(PredWrapper_EXT&& pred, CbWrapper_EXT&& cb):data{new Data{}}
		{
			buffer__Mutex.lock();
			data->it_ = buffer__.emplace_after(buffer__.before_begin(), move(pred),move(cb), SyncInfoPtr(new SyncInfo{}));
			buffer__Mutex.unlock();
		}
开发者ID:jhbsz,项目名称:kappaBox-SDK,代码行数:6,代码来源:aps_data_service_ext_impl.hpp

示例3: acquireUser

/* For sanitys sake I'm going to comment this one, since it's a
   doozy. The other two lookup functions are basically the same thing,
   so I'm only going to comment this one, and those comments also
   apply to the others.*/
lockptr<User> acquireUser(const long userID){
  userCacheManager.lock();
  // First thing, we check if we already have this user object cached.
  auto cacheIt = userCache.find(userID);
  // If we do, we can just lock the cached version, return it, and
  // we're done.
  if (cacheIt != userCache.end()){
    auto entry = cacheIt->second;
    userCacheManager.unlock();
    return lockptr<User>(entry->item, &(entry->m));
  }

  // If not, we want to first make room in the cache for a new object,
  // by kicking out the oldest one.
  for(auto it = userCache.begin(); it != userCache.end(); ++it){
    // Each cache entry has a ttl, which is initialized at the size of
    // the cache, and decremented every time we want to add something
    // new to the cache, so that if always we kick out objects with
    // non-positive TTL, we restrict our cache to the proper
    // size. Unfortunately, we might need to keep things in our cache
    // even if they have run out of life, because another thread might
    // still be holding on to them. This means that our cache might
    // grow above cachesize, but will never grow above
    // cachesize+number_of_threads.
    auto entry = it->second;
    if(--entry->ttl < 1 && entry->m.try_lock()){
      long entryID = it->first;
      // Now that we've decided to kick out this element, we need to
      // figure out if we still have a file mapping for it.  If not,
      // that means that that object was deleted already, so there's
      // no need to try to save it's state to a file.
      auto mapIt = userFileMap.find(entryID);
      if (mapIt != userFileMap.end())
	// If we do have a file mapping, we want to write out it's
	// current state, since any actions taken on it since it was
	// last pulled are in memory, but not in the file.
	entry->item->writeToFile(mapIt->second);
      // Since we, the cache, own the pointers to these objects, we
      // now need to clean it up, and finally remove the item from the
      // cache.
      delete entry->item;
      entry->m.unlock();
      delete entry;
      userCache.erase(it);
    }
  }
  // Next, we need to try to find the mapping for the file of the new
  // object we want to pull in. This might not succeed, since the
  // client could have an old ID for a user that has since been
  // deleted, so wee need to check for that, and return nullptr if so.
  auto mapIt = userFileMap.find(userID);
  if (mapIt == userFileMap.end()){
    userCacheManager.unlock();
    return lockptr<User>(nullptr, nullptr);
  }
  // Here, we finally load in the new User, taking ownership of the
  // pointer to it. Then, we update the cache with this new object,
  // and return the new object. We're done!
  User* loadedUser = User::readFromFile(mapIt->second);
  cacheRecord<User>* newEntry = new cacheRecord<User>();
  newEntry->item = loadedUser;
  newEntry->ttl = USER_CACHESIZE;
  userCache[userID] = newEntry;
  userCacheManager.unlock();
  return lockptr<User>(loadedUser, &(newEntry->m));
}
开发者ID:holdennb,项目名称:CollabCal,代码行数:70,代码来源:objectCache.cpp

示例4: INFO

int
_create(const char *path, mode_t mode, struct fuse_file_info *fi) {
    fi->flags &= O_TRUNC | O_CREAT | 0x3;
    fi->fh = -1;
    INFO("create [%s], mode = %04o, flags = %x\n", path, mode, fi->flags);

    int ret = 0;
    string t_p, t_b;
    split_path(path, t_p, t_b);

    _files_lock.lock();
    map<string, file_entry_t>::iterator p_it, t_it;
    if ((p_it = _files.find(t_p)) == _files.end()) {
        ret = -ENOENT;
    } else if ((t_it = _files.find(path)) != _files.end()) {
        if (fi->flags & O_EXCL) {
            ret = -EEXIST;
        } else {
            ret = _open_unsafe(path, fi);
        }
    } else {
        // path is ready and target file does not exists
        file_entry_t p = p_it->second;

        boost::uuids::uuid key_uuid = boost::uuids::random_generator()();
        string data_key = boost::lexical_cast<string>(key_uuid);

        string data_path;
        get_data_path(data_path, _data_store_base, data_key.c_str());

        int h = open(data_path.c_str(), fi->flags, mode);
        if (h == -1) {
            ret = -errno;
        } else {
            if (ftruncate(h, 0)) {
                DEBUG("FAIL to ftruncate, err=%d\n", errno);
            }
            
            file_entry_t fe = new_fe();
        
            fe->name = t_b;
            fe->st.st_mode = S_IFREG | (mode & 0777);
            fe->st.st_size = 0;

            fe->parent = p;
            list_add(&p->c_list, &fe->c_node);
            _files[path] = fe;

            fe->link = data_key;
            INFO("create assign key [%s] to [%s]\n", fe->link.c_str(), path);
            
            if (h >= FILE_DESC_UPPER_LIMIT) {
                DEBUG("create exceed the max number of fd\n");
                close(h);
                h = -1;
                ret = -ENOMEM;
            } else {
                fi->fh = h;
                
                fd_fe[h] = fe;
                fd_touch_size[h] = 0;
                
                fe_get(fe);
            
                fe->fetched = 1;
                fe->content_dirty = 1;
                fe->open_rc = 1;

                _update_queue.add(fe);
            }

            redis_sync(path, fe);
        }
    }
    _files_lock.unlock();

    if (ret < 0) {
        DEBUG("create [%s] error %d\n", path, ret);
    } else {
        // DEBUG("register fd %d [%s] %x\n", fi->fh, path, fi->flags);
    }

    return ret;
}
开发者ID:columbia,项目名称:grandet,代码行数:84,代码来源:main.cpp

示例5: update

    /**
     *  Vertex update function.
     */
    void update(CE_Graph_vertex<VertexDataType, EdgeDataType> &vertex, CE_Graph_context &gcontext) {
        if (gcontext.iteration == 0) {
            /* On first iteration, initialize vertex (and its edges). This is usually required, because
             on each run, CE_Graph will modify the data files. To start from scratch, it is easiest
             do initialize the program in code. Alternatively, you can keep a copy of initial data files. */

            latentvec_t latentfac;
            latentfac.init();
            set_latent_factor(vertex, latentfac);
        } else {
            mat XtX(NLATENT, NLATENT); 
            XtX.setZero();
            vec Xty(NLATENT);
            Xty.setZero();
            
            // Compute XtX and Xty (NOTE: unweighted)
            for(int e=0; e < vertex.num_edges(); e++) {
                float observation = vertex.edge(e)->get_data();                
                latentvec_t & nbr_latent = latent_factors_inmem[vertex.edge(e)->vertex_id()];
                for(int i=0; i<NLATENT; i++) {
                    Xty(i) += nbr_latent[i] * observation;
                    for(int j=i; j < NLATENT; j++) {
                        XtX(j,i) += nbr_latent[i] * nbr_latent[j];
                    }
                }
            }
            
            // Symmetrize
            for(int i=0; i <NLATENT; i++)
                for(int j=i + 1; j< NLATENT; j++) XtX(i,j) = XtX(j,i);
            
            // Diagonal
            for(int i=0; i < NLATENT; i++) XtX(i,i) += (LAMBDA) * vertex.num_edges();
            
            // Solve the least squares problem with eigen using Cholesky decomposition
            vec veclatent = XtX.ldlt().solve(Xty);
            
            // Convert to plain doubles (this is useful because now the output data by CE_Graph
            // is plain binary double matrix that can be read, for example, by Matlab).
            latentvec_t newlatent;
            for(int i=0; i < NLATENT; i++) newlatent[i] = veclatent[i];
            
            
            double sqerror = 0;
            bool compute_rmse = (gcontext.iteration == gcontext.num_iterations-1 && vertex.num_outedges() == 0);
            if (compute_rmse) { // Compute RMSE only on "right side" of bipartite graph
                for(int e=0; e < vertex.num_edges(); e++) {        
                    // Compute RMSE
                    float observation = vertex.edge(e)->get_data();
                    latentvec_t & nbr_latent =  latent_factors_inmem[vertex.edge(e)->vertex_id()];
                    double prediction = nbr_latent.dot(newlatent);
                    sqerror += (prediction - observation) * (prediction - observation);                
                    
                }
                rmselock.lock();
                rmse += sqerror;
                rmselock.unlock();
                
                if (vertex.id() % 5000 == 1) {
                    logstream(LOG_DEBUG) << "Computed RMSE for : " << vertex.id() << std::endl;
                }
            }
            
            set_latent_factor(vertex, newlatent); 
            
            if (vertex.id() % 100000 == 1) {
                std::cout <<  gcontext.iteration << ": " << vertex.id() << std::endl;
            }
        }
        
        /* Hack: we need to count ourselves the number of vertices on left
           and right side of the bipartite graph.
           TODO: maybe there should be specialized support for bipartite graphs in CE_Graph?
        */
        if (vertex.num_outedges() > 0) {
            // Left side on the bipartite graph
            if (vertex.id() > max_left_vertex) {
                lock.lock();
                max_left_vertex = std::max(vertex.id(), max_left_vertex);
                lock.unlock();
            }
        } else {
            if (vertex.id() > max_right_vertex) {
                lock.lock();
                max_right_vertex = std::max(vertex.id(), max_right_vertex);
                lock.unlock();
            }
        }

    }
开发者ID:carriercomm,项目名称:DPDK-Graph,代码行数:93,代码来源:als_vertices_inmem.cpp

示例6: connectHandler

void connectHandler(int sockfd, sockaddr_in servaddr, string clientInfo){
  //Attempt to connect to the server.
  //servaddr is server address
  if(connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0){
    fprintf(stderr, "connect error: %s\n", strerror(errno));
    exit(4);
  }
  //send sign and then send info:
  writeMsg("sign", sockfd); 
  //get sign on ack
  string ack; 
  readMsg(ack, sockfd); 
  if(ack.substr(0, 2) != "OK")
    printf("Could not connect to server\n"); 
  //sign onto the server:
  writeMsg(clientInfo, sockfd); 
  //once signed on begin talking to socket
  while(!SHUTDOWN){
    string message = "";
    string command = "";   
    int n; 
    char recvline[MAXLINE + 1]; 
    printf("Enter a command: ");
    std::getline(cin, command);
    if(command.substr(0, 6) == "status"){
      status(); 
    }
    else if(command.substr(0, 8) == "shutdown"){
      message = "gbye"; //server non-interactive command to shut down
      writeMsg(message, sockfd); 
      //talk to the server. (Application-level protocol)
      string cmp; 
      readMsg(cmp, sockfd); 
      if(cmp.substr(0, 4) == "shut"){
	if((close(sockfd)) < 0){
	  printf("error closing socket\n"); 
	}
	SHUTDOWN = true; 
	break;
      }
      else printf("Something went wrong with shutdown, please try again.\n"); 
    }
    else if(command.substr(0, 3) == "ls "){
      handleLsDirectory(command); 
      message = command; 
    }
    else if(command.substr(0, 2) == "ls"){
      handleLs(); //call the ls function to print directory contents
    }
    else if(command.substr(0, 4) == "list"){
      message = "list"; 
      int x;
      writeMsg(message, sockfd); 
      string clients;
      readMsg(clients, sockfd); 
      //display list to user
      displayList(clients); 
    }
    else if(command.substr(0, 5) == "share"){
      //the user wishes to share a file
      vector<string> splitString = split(command, ' '); 
      vector<string> splitFname = split(splitString.at(splitString.size() - 1), '/'); 
      string filename = splitFname.at(splitFname.size() - 1); 
      sharedFiles.lock(); 
      shareable.push_back(filename); 
      sharedFiles.unlock(); 
    }
    else if(command.substr(0, 8) == "download"){
      //split on spaces, store file name and path 
      vector<string> downloadCmd = split(command, ' ');
      if(downloadCmd.size() < 3) 
	printf("Incorrect download syntax. Like this: download <FILENAME> <FILEPATH>\n");
      else{
	string fileName = downloadCmd.at(1); //get the filename 
	string filePath = downloadCmd.at(2); //get the path of the file
	//search to see if file to download has been made available by 
	//one of our clients
	
	int found = searchFiles(fileName);
	if(found == -1){
	  printf("file not available for download\n"); 
	}
	else {
	  //begin download process:
	  //connect to the client that owns the file and ask to download it
	  //that client server then spawns a thread to do the ftp servers job
	  //and the client that wishes to download creates a thread to do the ftp client job
	  string downIp = connectedClients.at(found).ipAddr; 
	  int port = connectedClients.at(found).portNum; 
	  //now that we have this info we can make a connection and start the file transfer process.
	  int newsockfd, n;
	  struct sockaddr_in servaddr;
	  if((newsockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
	    fprintf(stderr, "Socket error.  %s\n", strerror(errno));
	    exit(2);
	  }
	  //build a profile for the client to whom we are going to
	  //communicate.
	  bzero(&servaddr, sizeof(servaddr));
	  servaddr.sin_family = AF_INET;
//.........这里部分代码省略.........
开发者ID:niklasrowen,项目名称:CS450,代码行数:101,代码来源:client.cpp

示例7: process

    // running in a dedicated thread
    void process() {
        int clear_index;
        {
            unique_lock<mutex> auto_lock(cur_lock);
            cond.wait(auto_lock);
            clear_index = (cur_index + 2) % 3;
            int next_index = (cur_index + 1) % 3;
            cur_index = next_index;
            cur_set = &queue[next_index];
        }
        auto back_set = &queue[clear_index];

        auto it = back_set->begin();
        while (it != back_set->end()) {
            file_entry_t fe = *it;
            grandet_sync_task_t sync_task = NULL;
            grandet_remove_task_t remove_task = NULL;
            _files_lock.lock();
            INFO("processing %s\n", fe->link.c_str());
            if (fe->deleted) {
                INFO("processing deleted fe, size=%ld, fetched=%d, open_rc=%d\n", fe->st.st_size, fe->fetched, fe->open_rc);
            }
            if (fe->deleted && fe->open_rc == 0) {
                // when it is out of tree, no one can open it anymore 
                if (fe->deleted == 1) {
                    string data_path;
                    if (fe->fetched)
                        cache_remove(fe->st.st_size);
                    get_data_path(data_path, _data_store_base, fe->link.c_str());
                    grandet_remove_task_start(fe->link.c_str(), data_path.c_str(), &remove_task);
                    grandet_remove_task_wait(remove_task);
                    grandet_remove_task_end(remove_task);
                    
                    fe->deleted = 2; // avoiding repeated deletion
                }
                fe_put(fe);
            } else {
                // Update
                if (fe->content_dirty) {
                    if (!S_ISREG(fe->st.st_mode)) {
                        DEBUG("flush a non-regular file");
                    }
                    
                    string data_path;
                    get_data_path(data_path, _data_store_base, fe->link.c_str());
                    
                    fe->content_dirty = 0;
                    grandet_sync_task_start(fe->link.c_str(), data_path.c_str(), fe->xattr, &sync_task);
                    
                    _files_lock.unlock();
                    grandet_sync_task_wait(sync_task);
                    grandet_sync_task_end(sync_task);
                    _files_lock.lock();

                    // during the unlock and lock, there may be some
                    // thread writing data in and close, causing
                    // content_dirty be 1 again. Or some one can even
                    // delete it.  In those cases, it will appear in
                    // update queue again.
                    if (fe->open_rc == 0 && fe->fetched == 1 &&
                        fe->content_dirty == 0 && fe->deleted == 0) {
                        // DEBUG("add %s to idle list\n", fe->link.c_str());
                        // LRU
                        if (!list_empty(&fe->u_node))
                            list_del_init(&fe->u_node);
                        INFO("add %s to idle_list (dirty)\n", fe->link.c_str());
                        list_add_before(&_idle_list, &fe->u_node);
                    }
                } else if (fe->fetched == 1 && fe->open_rc == 0) {
                    if (!list_empty(&fe->u_node))
                        list_del_init(&fe->u_node);
                    INFO("add %s to idle_list (clean)\n", fe->link.c_str());
                    list_add_before(&_idle_list, &fe->u_node);
                }
                fe_put(fe);
            }
            _files_lock.unlock();
            ++ it;
        }
        back_set->clear();
    }
开发者ID:columbia,项目名称:grandet,代码行数:82,代码来源:main.cpp

示例8: start_blocking

 /**
   Resumes operation of the fiber_blocking_queue. Future calls to
   dequeue will proceed as normal.
 */
 inline void start_blocking() {
     m_mutex.lock();
     m_alive = true;
     m_mutex.unlock();
 }
开发者ID:jamesbsilva,项目名称:Dato-Core,代码行数:9,代码来源:fiber_blocking_queue.hpp

示例9: broadcast

 /**
  * Causes any threads currently blocking on a dequeue to wake up
  * and evaluate the state of the queue. If the queue is empty,
  * the threads will return back to sleep immediately. If the queue
  * is destroyed through stop_blocking, all threads will return.
  */
 void broadcast() {
     m_mutex.lock();
     wake_all_fibers();
     m_mutex.unlock();
 }
开发者ID:jamesbsilva,项目名称:Dato-Core,代码行数:11,代码来源:fiber_blocking_queue.hpp

示例10: empty

 //! Returns true if the queue is empty
 inline bool empty() {
     m_mutex.lock();
     bool res = m_queue.empty();
     m_mutex.unlock();
     return res;
 }
开发者ID:jamesbsilva,项目名称:Dato-Core,代码行数:7,代码来源:fiber_blocking_queue.hpp

示例11: stop_blocking

 /** Wakes up all threads waiting on the queue whether
     or not an element is available. Once this function is called,
     all existing and future dequeue operations will return with failure.
     Note that there could be elements remaining in the queue after
     stop_blocking() is called.
 */
 inline void stop_blocking() {
     m_mutex.lock();
     m_alive = false;
     wake_all_fibers();
     m_mutex.unlock();
 }
开发者ID:jamesbsilva,项目名称:Dato-Core,代码行数:12,代码来源:fiber_blocking_queue.hpp

示例12: swap

 void swap(queue_type &q) {
     m_mutex.lock();
     q.swap(m_queue);
     m_mutex.unlock();
 }
开发者ID:jamesbsilva,项目名称:Dato-Core,代码行数:5,代码来源:fiber_blocking_queue.hpp

示例13: main

int main(){
	thread t(waitForKeyPress);

	list<CvPoint> opticalFlowVectors;

	//set up communicator	
	Communicator* comm = new Communicator(512, "192.168.2.3", 9002, "*", 9000);

	//receive size of one image
	char frameWidthBuf[3];
	char frameHeightBuf[3];
	comm->recv(frameWidthBuf, 3, 0);
	comm->recv(frameHeightBuf, 3, 0);
	//extract data
	int frameWidth = atoi(frameWidthBuf);
	int frameHeight = atoi(frameHeightBuf);
	int frameSize = frameWidth*frameHeight;

	cout << frameSize << endl;

	//declare frames
	Mat frame1(frameWidth,frameHeight,CV_8UC1);
	Mat frame2(frameWidth,frameHeight,CV_8UC1);

	//second get the image
	comm->recv(frame1.data, frameSize, 0);

	//build pyramid for frame 1
	buildOpticalFlowPyramid(frame1, pyramid1, cvSize(pyrWindowSize,pyrWindowSize), 3);


	//start optical flow algorithm
	cout << "Started optical flow algorithm." << endl;
	high_resolution_clock::time_point t1 = high_resolution_clock::now();
	int iter = 0;
    mtx.lock();
    while(loop)
    {
    	mtx.unlock();
    	
    	//recv frame 2
		comm->recv(frame2.data, frameSize, 0);

		FeatureDetector* detector = new FastFeatureDetector(FASTThreshold,true);
		detector->detect(frame1, KeyPointVector);
		delete detector;

		if(KeyPointVector.size() > 30)
			FASTThreshold++;
		else 
			FASTThreshold--;

		//build pyramid for frame 2
		buildOpticalFlowPyramid(frame2, pyramid2, cvSize(pyrWindowSize,pyrWindowSize), 3);
		KeyPoint::convert(KeyPointVector, pointVector1);

		//run Lucas Kanade optical flow if features have been found
		if(KeyPointVector.size() > 0)
		{
			calcOpticalFlowPyrLK(pyramid1, pyramid2, pointVector1,
			 pointVector2, featuresFound, featuresError,
			 cvSize(pyrWindowSize,pyrWindowSize), 0,
			 cvTermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 10, 0.2),
			 0,0.0001);
		}


		Mat frame3;
		cvtColor(frame2, frame3, CV_GRAY2RGB);

		for(int i=0; i < pointVector1.size(); i++){
			if(featuresFound[i]==0 || featuresError[i]>50)
			{
				//printf("Error is: %f\n",featuresError[i]);
				
			} else {
				CvPoint p0 = cvPoint(
						cvRound(pointVector1[i].x),
						cvRound(pointVector1[i].y));

				CvPoint p1 = cvPoint(
						cvRound(pointVector2[i].x),
						cvRound(pointVector2[i].y));

				line(frame3, p0, p1, CV_RGB(255,0,0), 1, 8, 0);
			}
		}

		ostringstream fileName2;
		fileName2 << "flightphoto/flow" << iter <<".jpg";
		imwrite(fileName2.str(), frame3);

		//store pyramid 2 in pyramid 1
		frame1 = frame2.clone();
		pyramid1.swap(pyramid2);

		//find the average displacement
		displacement = trajectoryCalc(pointVector1, pointVector2, featuresFound,
		 featuresError, KeyPointVector.size());
		//Compensate angle: must be done on RPI
//.........这里部分代码省略.........
开发者ID:kserruys,项目名称:ElisQuad,代码行数:101,代码来源:OpticalFlow.cpp

示例14: waitForKeyPress

void waitForKeyPress(){
	getchar();
	mtx.lock();
	loop = false;
	mtx.unlock();
}
开发者ID:kserruys,项目名称:ElisQuad,代码行数:6,代码来源:OpticalFlow.cpp

示例15: aicheng_topics_webpage

static void
downloadTopicPicsAndSeed ( const string& topic_url,
                           const string& proxy_addr,
                           const string& path,
                           unsigned timeout_download_pic,
                           bool b_show_info )
{
    AichengTopicWebpage aicheng_topics_webpage(topic_url, proxy_addr);

    // ready for the basename of pictures and seed.
    // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    string base_name; // from topic title

    // 0) delete the web logo info;
    // 1) clear the "/" in topictitle string, if the "/" present in filename,
    // linux will treat it as directory, again, clear the "\" for windows;
    static const vector<string> keyword_logos_list = { " 亚洲无码区 bt下载 - powered by phpwind.net",
                                                       " 亚洲有码区 bt下载 - powered by phpwind.net",
                                                       " 欧美区 bt下载 - powered by phpwind.net",
                                                       " 动漫区 bt下载 - powered by phpwind.net",
                                                       "|亚洲无码区 - bt下载 爱城 bt下载 ",
                                                       "亚洲无码区 - bt下载 爱城 bt下载 ",
                                                       "|亚洲有码区 - bt下载 爱城 bt下载 ",
                                                       "亚洲有码区 - bt下载 爱城 bt下载 ",
                                                       "|动漫区 - bt下载 爱城 bt下载 ",
                                                       "动漫区 - bt下载 爱城 bt下载 ",
                                                       "|欧美区 - bt下载 爱城 bt下载 ",
                                                       "欧美区 - bt下载 爱城 bt下载 " };
    const string& topic_webpage_title = aicheng_topics_webpage.getTitle();
    auto keyword_logo_pos = string::npos;
    for (const auto& f : keyword_logos_list) {
        keyword_logo_pos = topic_webpage_title.find(f);
        if (string::npos != keyword_logo_pos) {
            break;
        }
    }
    remove_copy_if( topic_webpage_title.cbegin(),
                    (string::npos == keyword_logo_pos) ? topic_webpage_title.cend() : topic_webpage_title.cbegin() + (int)keyword_logo_pos,
                    back_inserter(base_name),
                    [] (char ch) {return( '|' == ch || // invalid chars in windows-style filename
                                          '/' == ch ||
                                          '<' == ch ||
                                          '>' == ch ||
                                          '?' == ch ||
                                          '*' == ch ||
                                          ':' == ch ||
                                          '\\' == ch );} );

    // 2) the path + filename max length must less than pathconf(, _PC_NAME_MAX)
    const unsigned filename_max_length_without_postfix = (unsigned)pathconf(path.c_str(), _PC_NAME_MAX)
                                                         - string("99").size() // picture number
                                                         - string(".torrent").size();
    if (base_name.size() >= filename_max_length_without_postfix) {
        // the filename too long to create file. the way as following doesn't work, case filename encoding error: 
        // base_name.resize(filename_max_length_without_postfix - 1), because this is string on char not wstring on wchar.
        // there is another stupid way, random name from 'a' to 'z'
        base_name.resize(16);
        generate( base_name.begin(), base_name.end(), 
                  [] () {return('a' + rand() % ('z' - 'a'));} );
        base_name = "(rename)" + base_name;
    }
    // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
 
    // download all pictures
    vector<string> fail_download_pics_urls_list;
    bool b_download_pics_success = aicheng_topics_webpage.downloadAllPictures( path,
                                                                               base_name,
                                                                               timeout_download_pic,
                                                                               fail_download_pics_urls_list,
                                                                               32 );

    // download seed
    bool b_downloaded_seed_success = false;
    if (!aicheng_topics_webpage.getSeedUrl().empty()) {
        JandownSeedWebpage jan_seed_webpage(aicheng_topics_webpage.getSeedUrl(), proxy_addr);
        b_downloaded_seed_success = jan_seed_webpage.downloadSeed(path, base_name);
    }

    // show result info
    if (!b_show_info) {
        return;
    }
    static const string success_info("success");
    static const string fail_info = RichTxt::foreground_red + "failure" + RichTxt::reset_all;
    g_mtx.lock();
    cout << "  \"" << base_name << "\" - ";
    if (b_download_pics_success && b_downloaded_seed_success) {
        cout << success_info; 
    } else {
        cout << fail_info << " (download error from " << topic_url << ". ";
        if (!b_download_pics_success) {
            cout << "pictures error: ";
            copy(fail_download_pics_urls_list.cbegin(), fail_download_pics_urls_list.cend(), ostream_iterator<const string&>(cout, ", "));
            cout << "\b\b";
        }
        if (!b_downloaded_seed_success) {
            if (!b_download_pics_success) {
                cout << "; ";
            }
            cout << "seed error: " << aicheng_topics_webpage.getSeedUrl();
//.........这里部分代码省略.........
开发者ID:NichoZhang,项目名称:hardseed,代码行数:101,代码来源:Aicheng.cpp


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