• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C++ mutex类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: update

  /**
   *  Vertex update function - computes the least square step
   */
  void update(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, graphchi_context &gcontext) {

    //compute only for user nodes
    if (vertex.id() >= std::min(M,(uint)end_user) || vertex.id() < (uint)start_user)
      return;

    vertex_data & vdata = latent_factors_inmem[vertex.id()];
    int howmany = (int)(N*knn_sample_percent);
    assert(howmany > 0 );
    if (vertex.num_outedges() == 0){
       mymutex.lock();
       users_without_ratings++;
       mymutex.unlock();
    }

    vec distances = zeros(howmany);
    ivec indices = ivec::Zero(howmany);
    for (int i=0; i< howmany; i++){
      indices[i]= -1;
    }
    std::vector<bool> curratings;
    curratings.resize(N);
    for(int e=0; e < vertex.num_edges(); e++) {
      //no need to calculate this rating since it is given in the training data reference
      assert(vertex.edge(e)->vertex_id() - M >= 0 && vertex.edge(e)->vertex_id() - M < N);
      curratings[vertex.edge(e)->vertex_id() - M] = true;
    }
    if (knn_sample_percent == 1.0){
      for (uint i=M; i< M+N; i++){
        if (curratings[i-M])
          continue;
        vertex_data & other = latent_factors_inmem[i];
        double dist;
        if (algo == SVDPP)
          svdpp_predict(vdata, other, 0, dist); 
        else if (algo == BIASSGD) 
	  biassgd_predict(vdata, other, 0, dist);
        else if (algo == RBM)
          rbm_predict(vdata, other, 0, dist);
        else assert(false);
        indices[i-M] = i-M;
        distances[i-M] = dist + 1e-10;
      }
    }
    else for (int i=0; i<howmany; i++){
      int random_other = ::randi(M, M+N-1);
      vertex_data & other = latent_factors_inmem[random_other];
      double dist;
      if (algo == SVDPP)
        svdpp_predict(vdata, other, 0, dist); 
      else if (algo == BIASSGD)
        biassgd_predict(vdata, other, 0, dist);
      else if (algo == RBM)
        rbm_predict(vdata, other, 0, dist);
      else assert(false);
        
      indices[i] = random_other-M;
      distances[i] = dist;
    }

    vec out_dist(num_ratings);
    ivec indices_sorted = reverse_sort_index2(distances, indices, out_dist, num_ratings);
    assert(indices_sorted.size() <= num_ratings);
    assert(out_dist.size() <= num_ratings);
    vdata.ids = indices_sorted;
    vdata.ratings = out_dist;
    if (debug)
      printf("Closest is: %d with distance %g\n", (int)vdata.ids[0], vdata.ratings[0]);

    if (vertex.id() % 1000 == 0)
      printf("Computing recommendations for user %d at time: %g\n", vertex.id()+1, mytimer.current_time());
  }
开发者ID:CVML,项目名称:graphchi-cpp,代码行数:75,代码来源:rating2.cpp


示例2: broadcast_blocking_empty

 /**
  * Causes any threads blocking on "wait_until_empty()" to wake
  * up and evaluate the state of the queue. If the queue is not empty,
  * the threads will return back to sleep immediately. If the queue
  * is empty, all threads will return.
 */
 void broadcast_blocking_empty() {
   m_mutex.lock();
   m_empty_conditional.broadcast();
   m_mutex.unlock();
 }    
开发者ID:3upperm2n,项目名称:PowerGraph,代码行数:11,代码来源:blocking_queue.hpp


示例3: end_critical_section

 void end_critical_section() {
  m_mutex.unlock();
 }
开发者ID:3upperm2n,项目名称:PowerGraph,代码行数:3,代码来源:blocking_queue.hpp


示例4: start_blocking

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


示例5: 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


示例6: main

int main(int argc, char** argv)
{
    ros::init(argc, argv, "pathplanner");

    ros::NodeHandle nh;

    ros::Subscriber map_sub = nh.subscribe("/map", 1, map_callback);

    ros::Subscriber pose_sub = nh.subscribe("/odom_combined", 1, position_callback);

    ros::Subscriber waypoint_sub = nh.subscribe("/waypoint", 1, waypoint_callback);

    disp_path_pub = nh.advertise<nav_msgs::Path>("/path_display", 1);

    act_path_pub = nh.advertise<igvc_msgs::action_path>("/path", 1);

    expanded_pub = nh.advertise<pcl::PointCloud<pcl::PointXYZ> >("/expanded", 1);

    double baseline = 0.93;

    search_problem.Map = pcl::PointCloud<pcl::PointXYZ>().makeShared();
    search_problem.GoalThreshold = 1.0;
    search_problem.Threshold = 0.5;
    search_problem.Speed = 1.0;
    search_problem.Baseline = baseline;
    search_problem.DeltaT = [](double distToStart)->double {
        return 0.66*(log2(distToStart + 1) + 0.1);
    };
    search_problem.MinimumOmega = -0.6;
    search_problem.MaximumOmega = 0.61;
    search_problem.DeltaOmega = 0.5;
    search_problem.PointTurnsEnabled = false;
    search_problem.ReverseEnabled = false;
	search_problem.maxODeltaT = 0.1;

    ros::Rate rate(3);
    while(ros::ok())
    {
        ros::spinOnce();

        /* Do not attempt to plan a path if the path length would be greater than 100ft (~30m).
         * This should only happen when we have received either a waypoint or position estimate, but not both.
         * Long paths take forever to compute, and will freeze up this node.
         */
        auto distance_to_goal = search_problem.Start.distTo(search_problem.Goal);
        if(!received_waypoint || distance_to_goal == 0 || distance_to_goal > 60)
            continue;

        planning_mutex.lock();
        // TODO only replan if needed.
        auto path = GraphSearch::AStar(search_problem, expanded_callback);
        if(disp_path_pub.getNumSubscribers() > 0)
        {
            nav_msgs::Path disp_path_msg;
            disp_path_msg.header.stamp = ros::Time::now();
            disp_path_msg.header.frame_id = "map";
            if(path.getStates()->empty())
                path.getStates()->push_back(search_problem.Start);
            for(auto loc : *(path.getStates()))
            {
                geometry_msgs::PoseStamped pose;
                pose.header.stamp = disp_path_msg.header.stamp;
                pose.header.frame_id = disp_path_msg.header.frame_id;
                pose.pose.position.x = loc.x;
                pose.pose.position.y = loc.y;
                disp_path_msg.poses.push_back(pose);
            }
            disp_path_pub.publish(disp_path_msg);

            igvc_msgs::action_path act_path_msg;
            act_path_msg.header.stamp = ros::Time::now();
            act_path_msg.header.frame_id = "map";
            for(auto action : *(path.getActions()))
            {
                igvc_msgs::velocity_pair vels;
                vels.header.stamp = act_path_msg.header.stamp;
                vels.header.frame_id = act_path_msg.header.frame_id;
                double radius = action.V / action.W;
                vels.right_velocity = (radius - baseline/2.) * action.W;
                vels.left_velocity = (radius + baseline/2.) * action.W;
                vels.duration = action.DeltaT;
                act_path_msg.actions.push_back(vels);
            }
            act_path_pub.publish(act_path_msg);
        }

        planning_mutex.unlock();

        rate.sleep();
    }

    return 0;
}
开发者ID:jondolan,项目名称:igvc-software,代码行数:93,代码来源:main.cpp


示例7: lock

 void lock(error_code& ec = throws)
 {
     return lock("mutex::lock", ec);
 }
开发者ID:K-ballo,项目名称:hpx,代码行数:4,代码来源:mutex.hpp


示例8: try_lock

 bool try_lock(error_code& ec = throws)
 {
     return try_lock("mutex::try_lock", ec);
 }
开发者ID:K-ballo,项目名称:hpx,代码行数:4,代码来源:mutex.hpp


示例9: 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:3upperm2n,项目名称:PowerGraph,代码行数:7,代码来源:blocking_queue.hpp


示例10: 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();
   m_conditional.broadcast();
   m_mutex.unlock();
 }
开发者ID:3upperm2n,项目名称:PowerGraph,代码行数:11,代码来源:blocking_queue.hpp


示例11: SyncInfo

	namespace data_service_EXT{
		using namespace std;
		struct SyncInfo;

		using SyncInfoPtr 		= unique_ptr<SyncInfo>;
		using MsgRcvr___EXT		= tuple<PredWrapper_EXT, CbWrapper_EXT, SyncInfoPtr>;
		using HandlerBuffer 	=	forward_list<MsgRcvr___EXT>;
		HandlerBuffer buffer__;
		mutex buffer__Mutex;
		struct SyncInfo
		{
			mutex m{};
			condition_variable cv{};
			bool sync	{false};
			bool rdy	{false};
			SyncInfo(){}
			void arm()
			{
				sync = true;
				rdy = false;
			}
			bool wait_for(int64_t wait_time_us)
			{
				if (!sync)
					return false;
				unique_lock<mutex> lk{m};
				return cv.wait_for(lk, chrono::microseconds(wait_time_us), [this]{return rdy;});
			}
			void disarm()
			{
				if (!sync)
					return;
				sync 	= false;
				rdy 	= true;
				unique_lock<mutex> lk{m};
				cv.notify_one();
			}
		};

		struct TxHandle::Data
		{
			HandlerBuffer::iterator it_;
		};

		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();
		}
		TxHandle::~TxHandle()
		{
			delete data;
		}
		void TxHandle::arm()
		{
			get<2>(*data->it_)->arm();
		}
		bool TxHandle::wait_for(int64_t micro_sec)
		{
			return get<2>(*data->it_)->wait_for(micro_sec);
		}
		void TxHandle::remove()
		{
			buffer__Mutex.lock();
			swap(*(data->it_), buffer__.front());
			buffer__.pop_front();
			buffer__Mutex.unlock();
		}

		TxHandle registerHandlers(PredWrapper_EXT&& pred, CbWrapper_EXT&& cb)
		{
			return TxHandle{move(pred), move(cb)};
		}

		void	removeHandler(TxHandle& h)
		{
			h.remove();
		}

		void request(const AFMessage_EXT& msg)
		{
			sendAPSMessageStruct(const_cast<AFMessage_EXT*>(&msg));
		}

		void request(AFMessage_EXT& msg, PredWrapper_EXT&& pred, CbWrapper_EXT&& cb, int64_t wait_time_us)
		{
			//using namespace std::chrono;
			auto h = registerHandlers(move(pred),move(cb));
			h.arm();
			sendAPSMessageStruct(&msg);

			//auto t0 = steady_clock::now();
			if (h.wait_for(wait_time_us)){
				//LOG_MESSAGE("got it");
			}
//			else
//			{
//				LOG_MESSAGE("did not get it");
//			}
//.........这里部分代码省略.........
开发者ID:jhbsz,项目名称:kappaBox-SDK,代码行数:101,代码来源:aps_data_service_ext_impl.hpp


示例12: begin_critical_section

 void begin_critical_section() {
   m_mutex.lock();
 }
开发者ID:3upperm2n,项目名称:PowerGraph,代码行数:3,代码来源:blocking_queue.hpp


示例13: fftwf_free_thr

static void fftwf_free_thr(void *p) {
	static mutex m;
	m.lock();
	fftwf_free(p);
	m.unlock();
}
开发者ID:ICpachong,项目名称:superstitchous2.0,代码行数:6,代码来源:translate.cpp


示例14: sendreceive_usfmresources

void sendreceive_usfmresources ()
{
  mutex_sendreceive_usfmresources.lock ();
  bool bail_out = sendreceive_usfmresources_running;
  mutex_sendreceive_usfmresources.unlock ();
  if (bail_out) return;
  mutex_sendreceive_usfmresources.lock ();
  sendreceive_usfmresources_running = true;
  mutex_sendreceive_usfmresources.unlock ();
  
  
  Database_UsfmResources database_usfmresources = Database_UsfmResources ();
  Webserver_Request request;
  Sync_Logic sync_logic = Sync_Logic (&request);

  
  Database_Logs::log (sendreceive_usfmresources_sendreceive_text (), Filter_Roles::translator ());
  
 
  string address = Database_Config_General::getServerAddress ();
  int port = Database_Config_General::getServerPort ();
  string url = client_logic_url (address, port, sync_usfmresources_url ());

  
  map <string, string> post;
  string error;
  string response;
  
  
  // Request the checksum of all USFM resources from the server.
  // Compare it with the local checksum.
  // If the two match: Ready.
  post ["a"] = convert_to_string (Sync_Logic::usfmresources_get_total_checksum);
  response = sync_logic.post (post, url, error);
  if (!error.empty ()) {
    Database_Logs::log (sendreceive_usfmresources_text () + "Failure getting total checksum: " + error, Filter_Roles::translator ());
    sendreceive_usfmresources_done ();
    return;
  }
  string checksum = Sync_Logic::usfm_resources_checksum ();
  if (response == checksum) {
    Database_Logs::log (sendreceive_usfmresources_up_to_date_text (), Filter_Roles::translator ());
    sendreceive_usfmresources_done ();
    return;
  }
  
  
  // Request a list of all USFM resources available on the server.
  post ["a"] = convert_to_string (Sync_Logic::usfmresources_get_resources);
  response = sync_logic.post (post, url, error);
  if (!error.empty ()) {
    Database_Logs::log (sendreceive_usfmresources_text () + "Failure getting resources: " + error, Filter_Roles::translator ());
    sendreceive_usfmresources_done ();
    return;
  }
  vector <string> server_resources = filter_string_explode (response, '\n');
  
  
  // Delete any resource on the local client but not on the server.
  vector <string> client_resources = database_usfmresources.getResources ();
  vector <string> resources = filter_string_array_diff (client_resources, server_resources);
  for (auto & resource : resources) {
    database_usfmresources.deleteResource (resource);
  }
  
  
  // Deal with each USFM resource individually.
  for (auto & resource : server_resources) {
    
    
    // Request the checksum of the resources from the server.
    // Compare it with the checksum of the local resource.
    // If they match: Go to the next resource.
    post ["a"] = convert_to_string (Sync_Logic::usfmresources_get_resource_checksum);
    post ["r"] = resource;
    response = sync_logic.post (post, url, error);
    if (!error.empty ()) {
      Database_Logs::log (sendreceive_usfmresources_text () + "Failure getting checksum of resource: " + error, Filter_Roles::translator ());
      sendreceive_usfmresources_done ();
      return;
    }
    checksum = Sync_Logic::usfm_resource_checksum (resource);
    if (response == checksum) {
      continue;
    }
    

    // Request a list of all books in the resource on the server.
    post ["a"] = convert_to_string (Sync_Logic::usfmresources_get_books);
    post ["r"] = resource;
    response = sync_logic.post (post, url, error);
    if (!error.empty ()) {
      Database_Logs::log (sendreceive_usfmresources_text () + "Failure getting books of resource: " + error, Filter_Roles::translator ());
      sendreceive_usfmresources_done ();
      return;
    }
    vector <int> server_books;
    vector <string> sbooks = filter_string_explode (response, '\n');
    for (auto & book : sbooks) server_books.push_back (convert_to_int (book));

//.........这里部分代码省略.........
开发者ID:alerque,项目名称:bibledit,代码行数:101,代码来源:usfmresources.cpp


示例15: update

    /**
     *  Vertex update function.
     */
    void update(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, graphchi_context &gcontext) {
                if (gcontext.iteration == 0) {
            /* On first iteration, initialize vertex (and its edges). This is usually required, because
             on each run, GraphChi 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().weight;                
                latentvec_t nbr_latent = vertex.edge(e)->get_data().factor;
                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 GraphCHI
            // 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().weight;
                    latentvec_t nbr_latent = vertex.edge(e)->get_data().factor;
                    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 GraphChi?
        */
        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:yangzorror,项目名称:GraduationDesign,代码行数:93,代码来源:als_edgefactors.cpp


示例16: print_number

void print_number(int number){
    mu.lock();
    cout << number  << "\n";
    mu.unlock();
}
开发者ID:drodrigo,项目名称:becoming-a-ninja-challenge,代码行数:5,代码来源:simple_threads.cpp


示例17: saveTile

	void saveTile(int zoom, int x, int y, string *data) {
		int tmsY = pow(2,zoom) - 1 - y;
		m.lock();
		db << "REPLACE INTO tiles (zoom_level, tile_column, tile_row, tile_data) VALUES (?,?,?,?);" << zoom << x << tmsY && *data;
		m.unlock();
	}
开发者ID:systemed,项目名称:tilemaker,代码行数:6,代码来源:mbtiles.cpp


示例18: _release

static int _release(const char *path, struct fuse_file_info *fi) {
    INFO("release [%s]\n", path);

    if (fi->fh < 0 || fi->fh >= FILE_DESC_UPPER_LIMIT) {
        DEBUG("release invalid fd %lu, wtf\n", fi->fh);
        return -EINVAL;
    } else {
        // DEBUG("unregister fd %d\n", fi->fh);
    }
    
    _files_lock.lock();
    auto it = _files.find(path);
    file_entry_t fe;
    int mismatch = 1;
    
    if (it != _files.end()) {
        fe = it->second;
        if (fe->fetched > 0 && fe == fd_fe[fi->fh]) {
            mismatch = 0;
        
            _sync_fe_unsafe(path, fe, fi);
        
            -- fe->open_rc;
            INFO("  release: synced %s, open_rc=%d\n", path, fe->open_rc);
            fd_fe[fi->fh] = NULL;
            fd_touch_size[fi->fh] = 0;
            fe_put(fe);
            
            close(fi->fh);
            fi->fh = -1;
        }
    }

    if (mismatch) {
        if (fd_fe[fi->fh]) {
            fe = fd_fe[fi->fh];
            if (fe->open_rc <= 0) {
                DEBUG("release mismatch\n");
                check_fe(fe);
            } else if (fe->deleted) {
                // if it is removed, no more need to sync
                -- fe->open_rc;
                fd_fe[fi->fh] = NULL;
                fd_touch_size[fi->fh] = 0;
                fe_put(fe);

                close(fi->fh);
            } else {
                // moved to other place
                // sync with real path
                string real_path;
                if (get_real_path(fe, real_path) == 0) {
                    _sync_fe_unsafe(real_path.c_str(), fe, fi);
                } else {
                    DEBUG("get_real_path failed in release\n");
                }

                -- fe->open_rc;
                fd_fe[fi->fh] = NULL;
                fd_touch_size[fi->fh] = 0;
                fe_put(fe);
                
                close(fi->fh);
                fi->fh = -1;
            }

        } else {
            if (fcntl(fi->fh, F_GETFD) == -1) {
                DEBUG("release a NULL fe? the fd %lu is invalid\n", fi->fh);
            } else {
                DEBUG("release a NULL fe? the fd %lu is valid\n", fi->fh);
            }
        }
    }
#ifdef FLUSH_CACHE_ON_RELEASE
    cache_add(0);
#endif
    _files_lock.unlock();

    fi->fh = -1;
    return 0;
}
开发者ID:columbia,项目名称:grandet,代码行数:82,代码来源:main.cpp


示例19: wait

 /**
  * Waits for all replies to complete. It is up to the 
  * reply implementation to decrement the counter.
  */
 inline void wait() {
   mut.lock();
   while(!valready) cond.wait(mut);
   mut.unlock();
 }
开发者ID:Hannah1999,项目名称:Dato-Core,代码行数:9,代码来源:request_reply_handler.hpp


示例20: 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



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ mutex_t类代码示例发布时间:2022-05-31
下一篇:
C++ mutation_ptr类代码示例发布时间:2022-05-31
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap