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


C++ Process类代码示例

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


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

示例1: log

SBValue
SBFrame::FindValue (const char *name, ValueType value_type, lldb::DynamicValueType use_dynamic)
{
    LogSP log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API));
    SBValue sb_value;
    
    if (name == NULL || name[0] == '\0')
    {
        if (log)
            log->Printf ("SBFrame::FindValue called with empty name.");
        return sb_value;
    }
    
    ValueObjectSP value_sp;
    Mutex::Locker api_locker;
    ExecutionContext exe_ctx (m_opaque_sp.get(), api_locker);

    StackFrame *frame = NULL;
    Target *target = exe_ctx.GetTargetPtr();
    Process *process = exe_ctx.GetProcessPtr();
    if (target && process)
    {
        Process::StopLocker stop_locker;
        if (stop_locker.TryLock(&process->GetRunLock()))
        {
            frame = exe_ctx.GetFramePtr();
            if (frame)
            {
                switch (value_type)
                {
                case eValueTypeVariableGlobal:      // global variable
                case eValueTypeVariableStatic:      // static variable
                case eValueTypeVariableArgument:    // function argument variables
                case eValueTypeVariableLocal:       // function local variables
                    {
                        VariableList *variable_list = frame->GetVariableList(true);

                        SymbolContext sc (frame->GetSymbolContext (eSymbolContextBlock));

                        const bool can_create = true;
                        const bool get_parent_variables = true;
                        const bool stop_if_block_is_inlined_function = true;

                        if (sc.block && sc.block->AppendVariables (can_create, 
                                                                   get_parent_variables,
                                                                   stop_if_block_is_inlined_function,
                                                                   variable_list))
                        {
                            ConstString const_name(name);
                            const uint32_t num_variables = variable_list->GetSize();
                            for (uint32_t i = 0; i < num_variables; ++i)
                            {
                                VariableSP variable_sp (variable_list->GetVariableAtIndex(i));
                                if (variable_sp && 
                                    variable_sp->GetScope() == value_type &&
                                    variable_sp->GetName() == const_name)
                                {
                                    value_sp = frame->GetValueObjectForFrameVariable (variable_sp, eNoDynamicValues);
                                    sb_value.SetSP (value_sp, use_dynamic);
                                    break;
                                }
                            }
                        }
                    }
                    break;

                case eValueTypeRegister:            // stack frame register value
                    {
                        RegisterContextSP reg_ctx (frame->GetRegisterContext());
                        if (reg_ctx)
                        {
                            const uint32_t num_regs = reg_ctx->GetRegisterCount();
                            for (uint32_t reg_idx = 0; reg_idx < num_regs; ++reg_idx)
                            {
                                const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex (reg_idx);
                                if (reg_info && 
                                    ((reg_info->name && strcasecmp (reg_info->name, name) == 0) ||
                                     (reg_info->alt_name && strcasecmp (reg_info->alt_name, name) == 0)))
                                {
                                    value_sp = ValueObjectRegister::Create (frame, reg_ctx, reg_idx);
                                    sb_value.SetSP (value_sp);
                                    break;
                                }
                            }
                        }
                    }
                    break;

                case eValueTypeRegisterSet:         // A collection of stack frame register values
                    {
                        RegisterContextSP reg_ctx (frame->GetRegisterContext());
                        if (reg_ctx)
                        {
                            const uint32_t num_sets = reg_ctx->GetRegisterSetCount();
                            for (uint32_t set_idx = 0; set_idx < num_sets; ++set_idx)
                            {
                                const RegisterSet *reg_set = reg_ctx->GetRegisterSet (set_idx);
                                if (reg_set && 
                                    ((reg_set->name && strcasecmp (reg_set->name, name) == 0) ||
                                     (reg_set->short_name && strcasecmp (reg_set->short_name, name) == 0)))
//.........这里部分代码省略.........
开发者ID:filcab,项目名称:lldb,代码行数:101,代码来源:SBFrame.cpp

示例2: startSJF

//Purpose: Runs the shortest job first algorithm
//Parameters: The number of processes (int numOfP)
void startSJF(int numOfP){
  std::cout << std::endl << "Starting SJF Simulation...\n" << std::endl;
  //queues for simulation
  std::priority_queue< Event, std::vector<Event>, Event::CompTime> eventQueue;//event queue for holding various events
  std::priority_queue< Process, std::vector<Process>, Process::CompDur > readyQueue;//ready queue for holding processes
  std::priority_queue< Process, std::vector<Process>, Process::CompIO > IOArray;//used for holding process that are waiting for an IO device


  std::priority_queue< Event, std::vector<Event>, Event::CompTime> tempEventQueue;
  std::priority_queue< Process, std::vector<Process>, Process::CompDur > tempProcessQueue;

  std::vector<Process> ProcessArray;//used for final output

  //Time variables
  double totalTime = 300.0;//total time executed
  double currentTime = 0.0;//Initialize current time
  double randomDouble = 0.0;//used for various things

  int currentEvent;//holds the current event type
  Process newP;//used for new processes
  Process CPUProcess;//process in the CPU
  int IDcount = 0;//for the process IDs
  bool CPUBusy = false;//flag for checking if the CPU has a process in it
  double CPUIdleTime = 0.0;//time that the CPU was not working
  double CPUIdleTimeTemp = 0.0;//assists finding CPU idle time
  

  srand(time(0));//set random seed
  Event newE;//temporary event holder
  long n = -2;//for random numbers


  for (int i = 0; i < numOfP; i++){
    newE.setEventType(1);//new event = process arrival
    randomDouble = ( rand() % 300000 );
    randomDouble = randomDouble/1000;
    newE.setTimeOfEvent(rand() % 299 + ran1(&n));
    eventQueue.push(newE);
    //std::cout << newE.getTimeOfEvent() << std::endl;
  }

  
  int tempI; //not needed
  while ((!eventQueue.empty())){

    currentEvent = eventQueue.top().getEventType();
    currentTime = eventQueue.top().getTimeOfEvent();
    eventQueue.pop();//erase front event
    switch(currentEvent){
    case 1://Process Arrival
      
      //adds to the ready queue
      randomDouble = ( rand() % 60000 );
      randomDouble = randomDouble/1000;
      newP.setTotalDuration(randomDouble);

      //average burst
      randomDouble = ( rand() % 95 ) + 5;
      newP.setAverageBurst(randomDouble);//Ϯn+1 = αᵼn + (1 - α)Ϯn


      newP.setStatus("Ready");
      newP.setProcessID(IDcount);
      newP.setArrivalTime(currentTime);
      newP.setRemainingDuration(0.0);
      newP.setIOBurst(0.0);
      newP.setIOBurstTotal(0.0);
      newP.setWaitingTime(0.0);
      newP.setLastRun(0.0);
      IDcount++;//increment ID, next ID will be the ID of current process + 1

      //set next burst
      randomDouble = CPUBurstRandom(newP.getAverageBurst());
      randomDouble = randomDouble/1000;
      if(randomDouble <= 0.0){randomDouble += 0.001;}//CPUBurstRandom() can generate 0.0 sometimes
      newP.setNextBurst(randomDouble);
      readyQueue.push(newP);//push it to the back


      //checks the CPU to see if it is busy
      if (CPUBusy){

      }
      else{//if it isnt, add the new process into the CPU
	CPUBusy = true;
	CPUIdleTime = (currentTime - CPUIdleTimeTemp) + CPUIdleTime;
	CPUProcess = readyQueue.top();
	CPUProcess.setStatus("Running");
	//std::cout << "CPUProcess: " << CPUProcess.getProcessID() <<  " Inserted" <<std::endl;
	
	readyQueue.pop();//erase front event
	newE.setEventType(2);
	newE.setTimeOfEvent(currentTime+CPUProcess.getNextBurst());
	//add the event completion time to the event queue
	//std::cout << "Event Processes at: " << newE.getTimeOfEvent() << std::endl;
	eventQueue.push(newE);
      }

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

示例3: main

extern int main ( int argc, char *argv[] ) {

  /**************************************************************************
   * Register self.                                                         *
   **************************************************************************/

   Sys_RegisterThread ( ) ;

  /**************************************************************************
   * Set a default exception filter.                                        *
   **************************************************************************/

   REGISTER_EXCEPTION_HANDLER(0);

  /**************************************************************************
   * Start the main block (for constructors/destructors).                   *
   **************************************************************************/

   {

  /**************************************************************************
   * Get the initial file path for loading files from command-line.         *
   **************************************************************************/

   char InitialPath [CCHMAXPATH] ;
   _fullpath ( InitialPath, ".", sizeof(InitialPath) ) ;
   strcat ( InitialPath, "\\" ) ;

  /**************************************************************************
   * Determine the home directory.                                          *
   **************************************************************************/

   char Drive [_MAX_DRIVE+1], Dir[_MAX_DIR+1], Fname[_MAX_FNAME+1], Ext[_MAX_EXT+1] ;
   strupr ( argv[0] ) ;
   _fullpath ( HomePath, argv[0], sizeof(HomePath) ) ;
   _splitpath ( HomePath, Drive, Dir, Fname, Ext ) ;
   if ( Dir[strlen(Dir)-1] == '\\' )
      Dir[strlen(Dir)-1] = 0 ;
   strcpy ( HomePath, Drive ) ;
   strcat ( HomePath, Dir ) ;

   _chdrive ( Drive[0] - 'A' + 1 ) ;
   _chdir ( "\\" ) ;
   _chdir ( Dir ) ;

  /**************************************************************************
   * Set the C RunTime Library error message file handle.                   *
   **************************************************************************/

   #ifdef __DEBUG_ALLOC__
      Log ( "Escriba::main: Program started." ) ;
      _set_crt_msg_handle ( fileno(Logfile) ) ;
   #else
      #ifdef DEBUG
         Log ( "Escriba::main: Program started." ) ;
      #endif // DEBUG
   #endif // __DEBUG_ALLOC__

  /**************************************************************************
   * Determine if another instance of this program is present.              *
   *   If so, pass the command-line information to it.                      *
   **************************************************************************/

   #ifdef DEBUG
      Log ( "Escriba::main: Checking for another instance already loaded." ) ;
   #endif // DEBUG

   PublicMemory Memory ( MEMORY_NAME, sizeof(SHARED_MEMORY), TRUE ) ;
   if ( NOT Memory.QueryCreated() ) {

      // Get the main instance's window handle.  Wait up to 20 seconds if necessary.
      HWND MainWindow = ((SHARED_MEMORY*)Memory.QueryMemory())->MainWindow ;
      clock_t LastClock = clock ( ) ;
      while ( MainWindow == 0 ) {
         if ( ( ( clock() - LastClock ) / CLOCKS_PER_SEC ) > 20 ) {
            Log ( "ERROR: Unable to get previous instance window handle." ) ;
            return ( 1 ) ;
         } /* endif */
         DosSleep ( 100 ) ;
         MainWindow = ((SHARED_MEMORY*)Memory.QueryMemory())->MainWindow ;
      } /* endwhile */

      // If any command-line parameters were given . . .
      if ( argc > 1 ) {

         // Build a command-line string.
         char Parms [512] = { 0 } ;
         int ParmLength = 0 ;
         while ( --argc ) {
            strcpy ( Parms+ParmLength, *(++argv) ) ;
            ParmLength += strlen(*argv) + 1 ;
         } /* endwhile */
         Parms[++ParmLength] = 0 ;

         // Get the original process's ID.
         PID Process ;
         TID Thread ;
         if ( !WinQueryWindowProcess ( MainWindow, &Process, &Thread ) ) {
            char Message [512] ;
            Log ( "ERROR: Unable to query window process.  %s", InterpretWinError(0,Message) ) ;
//.........这里部分代码省略.........
开发者ID:OS2World,项目名称:APP-PRODUCTIVITY-Escriba,代码行数:101,代码来源:ESCRIBA.CPP

示例4: log

Error
ClangExpressionParser::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, RecordingMemoryManager *jit_memory_manager)
{
    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
    
    const char *name = m_expr.FunctionName();
    
    Error ret;
    
    ret.Clear();
    
    lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
    lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
    
    std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
    
    for (pos = m_jitted_functions.begin(); pos < end; pos++)
    {
        if (strstr(pos->m_name.c_str(), name))
        {
            func_local_addr = pos->m_local_addr;
            func_remote_addr = pos->m_remote_addr;
        }
    }
    
    if (func_local_addr == LLDB_INVALID_ADDRESS)
    {
        ret.SetErrorToGenericError();
        ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
        return ret;
    }
    
    if (log)
        log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
    
    std::pair <lldb::addr_t, lldb::addr_t> func_range;
    
    func_range = jit_memory_manager->GetRemoteRangeForLocal(func_local_addr);
    
    if (func_range.first == 0 && func_range.second == 0)
    {
        ret.SetErrorToGenericError();
        ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
        return ret;
    }
    
    if (log)
        log->Printf("Function's code range is [0x%llx+0x%llx]", func_range.first, func_range.second);
    
    Target *target = exe_ctx.GetTargetPtr();
    if (!target)
    {
        ret.SetErrorToGenericError();
        ret.SetErrorString("Couldn't find the target");
    }
    
    lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second, 0));
    
    Process *process = exe_ctx.GetProcessPtr();
    Error err;
    process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
    
    if (!err.Success())
    {
        ret.SetErrorToGenericError();
        ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
        return ret;
    }
    
    ArchSpec arch(target->GetArchitecture());
    
    Disassembler *disassembler = Disassembler::FindPlugin(arch, NULL);
    
    if (disassembler == NULL)
    {
        ret.SetErrorToGenericError();
        ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.GetArchitectureName());
        return ret;
    }
    
    if (!process)
    {
        ret.SetErrorToGenericError();
        ret.SetErrorString("Couldn't find the process");
        return ret;
    }
    
    DataExtractor extractor(buffer_sp, 
                            process->GetByteOrder(),
                            target->GetArchitecture().GetAddressByteSize());
    
    if (log)
    {
        log->Printf("Function data has contents:");
        extractor.PutToLog (log.get(),
                            0,
                            extractor.GetByteSize(),
                            func_remote_addr,
                            16,
                            DataExtractor::TypeUInt8);
//.........这里部分代码省略.........
开发者ID:ztianjin,项目名称:lldb,代码行数:101,代码来源:ClangExpressionParser.cpp

示例5: exe_ctx

//----------------------------------------------------------------------
// Static callback function that gets called when our DYLD notification
// breakpoint gets hit. We update all of our image infos and then
// let our super class DynamicLoader class decide if we should stop
// or not (based on global preference).
//----------------------------------------------------------------------
bool DynamicLoaderMacOSXDYLD::NotifyBreakpointHit(
    void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
    lldb::user_id_t break_loc_id) {
  // Let the event know that the images have changed
  // DYLD passes three arguments to the notification breakpoint.
  // Arg1: enum dyld_image_mode mode - 0 = adding, 1 = removing
  // Arg2: uint32_t infoCount        - Number of shared libraries added
  // Arg3: dyld_image_info info[]    - Array of structs of the form:
  //                                     const struct mach_header
  //                                     *imageLoadAddress
  //                                     const char               *imageFilePath
  //                                     uintptr_t imageFileModDate (a time_t)

  DynamicLoaderMacOSXDYLD *dyld_instance = (DynamicLoaderMacOSXDYLD *)baton;

  // First step is to see if we've already initialized the all image infos.  If
  // we haven't then this function
  // will do so and return true.  In the course of initializing the
  // all_image_infos it will read the complete
  // current state, so we don't need to figure out what has changed from the
  // data passed in to us.

  ExecutionContext exe_ctx(context->exe_ctx_ref);
  Process *process = exe_ctx.GetProcessPtr();

  // This is a sanity check just in case this dyld_instance is an old dyld
  // plugin's breakpoint still lying around.
  if (process != dyld_instance->m_process)
    return false;

  if (dyld_instance->InitializeFromAllImageInfos())
    return dyld_instance->GetStopWhenImagesChange();

  const lldb::ABISP &abi = process->GetABI();
  if (abi) {
    // Build up the value array to store the three arguments given above, then
    // get the values from the ABI:

    ClangASTContext *clang_ast_context =
        process->GetTarget().GetScratchClangASTContext();
    ValueList argument_values;
    Value input_value;

    CompilerType clang_void_ptr_type =
        clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
    CompilerType clang_uint32_type =
        clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(
            lldb::eEncodingUint, 32);
    input_value.SetValueType(Value::eValueTypeScalar);
    input_value.SetCompilerType(clang_uint32_type);
    //        input_value.SetContext (Value::eContextTypeClangType,
    //        clang_uint32_type);
    argument_values.PushValue(input_value);
    argument_values.PushValue(input_value);
    input_value.SetCompilerType(clang_void_ptr_type);
    //        input_value.SetContext (Value::eContextTypeClangType,
    //        clang_void_ptr_type);
    argument_values.PushValue(input_value);

    if (abi->GetArgumentValues(exe_ctx.GetThreadRef(), argument_values)) {
      uint32_t dyld_mode =
          argument_values.GetValueAtIndex(0)->GetScalar().UInt(-1);
      if (dyld_mode != static_cast<uint32_t>(-1)) {
        // Okay the mode was right, now get the number of elements, and the
        // array of new elements...
        uint32_t image_infos_count =
            argument_values.GetValueAtIndex(1)->GetScalar().UInt(-1);
        if (image_infos_count != static_cast<uint32_t>(-1)) {
          // Got the number added, now go through the array of added elements,
          // putting out the mach header
          // address, and adding the image.
          // Note, I'm not putting in logging here, since the AddModules &
          // RemoveModules functions do
          // all the logging internally.

          lldb::addr_t image_infos_addr =
              argument_values.GetValueAtIndex(2)->GetScalar().ULongLong();
          if (dyld_mode == 0) {
            // This is add:
            dyld_instance->AddModulesUsingImageInfosAddress(image_infos_addr,
                                                            image_infos_count);
          } else {
            // This is remove:
            dyld_instance->RemoveModulesUsingImageInfosAddress(
                image_infos_addr, image_infos_count);
          }
        }
      }
    }
  } else {
    process->GetTarget().GetDebugger().GetAsyncErrorStream()->Printf(
        "No ABI plugin located for triple %s -- shared libraries will not be "
        "registered!\n",
        process->GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
//.........这里部分代码省略.........
开发者ID:karwa,项目名称:swift-lldb,代码行数:101,代码来源:DynamicLoaderMacOSXDYLD.cpp

示例6: SetValueIsValid

bool ValueObjectDynamicValue::UpdateValue() {
  SetValueIsValid(false);
  m_error.Clear();

  if (!m_parent->UpdateValueIfNeeded(false)) {
    // The dynamic value failed to get an error, pass the error along
    if (m_error.Success() && m_parent->GetError().Fail())
      m_error = m_parent->GetError();
    return false;
  }

  // Setting our type_sp to NULL will route everything back through our parent
  // which is equivalent to not using dynamic values.
  if (m_use_dynamic == lldb::eNoDynamicValues) {
    m_dynamic_type_info.Clear();
    return true;
  }

  ExecutionContext exe_ctx(GetExecutionContextRef());
  Target *target = exe_ctx.GetTargetPtr();
  if (target) {
    m_data.SetByteOrder(target->GetArchitecture().GetByteOrder());
    m_data.SetAddressByteSize(target->GetArchitecture().GetAddressByteSize());
  }

  // First make sure our Type and/or Address haven't changed:
  Process *process = exe_ctx.GetProcessPtr();
  if (!process)
    return false;

  TypeAndOrName class_type_or_name;
  Address dynamic_address;
  bool found_dynamic_type = false;
  Value::ValueType value_type;

  LanguageRuntime *runtime = nullptr;

  lldb::LanguageType known_type = m_parent->GetObjectRuntimeLanguage();
  if (known_type != lldb::eLanguageTypeUnknown &&
      known_type != lldb::eLanguageTypeC) {
    runtime = process->GetLanguageRuntime(known_type);
    if (runtime)
      found_dynamic_type = runtime->GetDynamicTypeAndAddress(
          *m_parent, m_use_dynamic, class_type_or_name, dynamic_address,
          value_type);
  } else {
    runtime = process->GetLanguageRuntime(lldb::eLanguageTypeC_plus_plus);
    if (runtime)
      found_dynamic_type = runtime->GetDynamicTypeAndAddress(
          *m_parent, m_use_dynamic, class_type_or_name, dynamic_address,
          value_type);

    if (!found_dynamic_type) {
      runtime = process->GetLanguageRuntime(lldb::eLanguageTypeObjC);
      if (runtime)
        found_dynamic_type = runtime->GetDynamicTypeAndAddress(
            *m_parent, m_use_dynamic, class_type_or_name, dynamic_address,
            value_type);
    }
  }

  // Getting the dynamic value may have run the program a bit, and so marked us
  // as needing updating, but we really don't...

  m_update_point.SetUpdated();

  if (runtime && found_dynamic_type) {
    if (class_type_or_name.HasType()) {
      m_type_impl =
          TypeImpl(m_parent->GetCompilerType(),
                   runtime->FixUpDynamicType(class_type_or_name, *m_parent)
                       .GetCompilerType());
    } else {
      m_type_impl.Clear();
    }
  } else {
    m_type_impl.Clear();
  }

  // If we don't have a dynamic type, then make ourselves just a echo of our
  // parent. Or we could return false, and make ourselves an echo of our
  // parent?
  if (!found_dynamic_type) {
    if (m_dynamic_type_info)
      SetValueDidChange(true);
    ClearDynamicTypeInformation();
    m_dynamic_type_info.Clear();
    m_value = m_parent->GetValue();
    m_error = m_value.GetValueAsData(&exe_ctx, m_data, 0, GetModule().get());
    return m_error.Success();
  }

  Value old_value(m_value);

  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));

  bool has_changed_type = false;

  if (!m_dynamic_type_info) {
    m_dynamic_type_info = class_type_or_name;
//.........这里部分代码省略.........
开发者ID:FreeBSDFoundation,项目名称:freebsd,代码行数:101,代码来源:ValueObjectDynamicValue.cpp

示例7: ReceiveAckFromParticipant

// thread for receiving ACK messages from ONE participant
void* ReceiveAckFromParticipant(void* _rcv_thread_arg) {
    ReceiveThreadArgument *rcv_thread_arg = (ReceiveThreadArgument *)_rcv_thread_arg;
    int pid = rcv_thread_arg->pid;
    int tid = rcv_thread_arg->transaction_id;
    string msg1 = rcv_thread_arg->expected_msg1;    //ACK
    string msg2 = rcv_thread_arg->expected_msg2;    //NULL
    Process *p = rcv_thread_arg->p;

    char buf[kMaxDataSize];
    int num_bytes;
    //TODO: write code to extract multiple messages

    fd_set temp_set;
    FD_ZERO(&temp_set);
    FD_SET(p->get_fd(pid), &temp_set);
    int fd_max = p->get_fd(pid);
    int rv;
    rv = select(fd_max + 1, &temp_set, NULL, NULL, (timeval*)&kTimeout);
    if (rv == -1) { //error in select
        // cout << "P" << p->get_pid() << ": ERROR in select() for P" << pid << strerror(errno)<< endl;
        rcv_thread_arg->received_msg_type = TIMEOUT;
        p->RemoveFromUpSet(pid);
    } else if (rv == 0) {   //timeout
        rcv_thread_arg->received_msg_type = TIMEOUT;
        p->RemoveFromUpSet(pid);
    } else {    // activity happened on the socket
        if ((num_bytes = recv(p->get_fd(pid), buf, kMaxDataSize - 1, 0)) == -1) {
            // cout << "P" << p->get_pid() << ": ERROR in receiving for P" << pid << endl;
            rcv_thread_arg->received_msg_type = TIMEOUT;
            p->RemoveFromUpSet(pid);
        } else if (num_bytes == 0) {     //connection closed
            // cout << "P" << p->get_pid() << ": Connection closed by P" << pid << endl;
            // if participant closes connection, it is equivalent to it crashing
            // can treat it as TIMEOUT
            // TODO: verify argument
            rcv_thread_arg->received_msg_type = TIMEOUT;
            p->RemoveFromUpSet(pid);
            //TODO: handle connection close based on different cases
        } else {
            buf[num_bytes] = '\0';
            cout << "P" << p->get_pid() << ": ACK received from P" << pid <<  endl;

            string extracted_msg;
            int received_tid;
            // in this case, we don't care about the received_tid,
            // because it will surely be for the transaction under consideration
            p->ExtractMsg(string(buf), extracted_msg, received_tid);

            if (extracted_msg == msg1) {    // it's an ACK
                rcv_thread_arg->received_msg_type = ACK;
            } else {
                //TODO: take actions appropriately, like check log for previous transaction decision.
                timeval timeofday;
                gettimeofday(&timeofday, NULL);
                cout << "P" << p->get_pid() << ": Expecting ack. Unexpected msg received from P" << pid << buf<< " at "<<timeofday.tv_sec<<"."<<timeofday.tv_usec<<endl;

                rcv_thread_arg->received_msg_type = ERROR;
            }
        }
    }
    // cout << "P" << p->get_pid() << ": Receive thread exiting for P" << pid << endl;
    return NULL;
}
开发者ID:shobhit6993,项目名称:3-phase-commit,代码行数:64,代码来源:coordinator.cpp

示例8: catch

Maps::Maps(DFContextShared* _d)
{
    d = new Private;
    d->d = _d;
    Process *p = d->owner = _d->p;
    d->Inited = d->FeaturesStarted = d->Started = false;
    d->block = NULL;
    d->usesWorldDataPtr = false;

    DFHack::VersionInfo * mem = p->getDescriptor();
    Private::t_offsets &off = d->offsets;
    d->hasFeatures = d->hasGeology = d->hasVeggies = true;

    // get the offsets once here
    OffsetGroup *OG_Maps = mem->getGroup("Maps");
    try
    {
        off.world_data = OG_Maps->getAddress("world_data");
        d->usesWorldDataPtr = true;
        //cout << "uses world ptr" << endl;
    }catch(Error::AllMemdef &){}

    {
        off.map_offset = OG_Maps->getAddress ("map_data");
        off.x_count_offset = OG_Maps->getAddress ("x_count_block");
        off.y_count_offset = OG_Maps->getAddress ("y_count_block");
        off.z_count_offset = OG_Maps->getAddress ("z_count_block");
        off.region_x_offset = OG_Maps->getAddress ("region_x");
        off.region_y_offset = OG_Maps->getAddress ("region_y");
        off.region_z_offset =  OG_Maps->getAddress ("region_z");
        if(d->usesWorldDataPtr)
        {
            off.world_size_x = OG_Maps->getOffset ("world_size_x_from_wdata");
            off.world_size_y = OG_Maps->getOffset ("world_size_y_from_wdata");
        }
        else
        {
            off.world_size_x = OG_Maps->getAddress ("world_size_x");
            off.world_size_y = OG_Maps->getAddress ("world_size_y");
        }
        OffsetGroup *OG_MapBlock = OG_Maps->getGroup("block");
        {
            off.tile_type_offset = OG_MapBlock->getOffset ("type");
            off.designation_offset = OG_MapBlock->getOffset ("designation");
            off.occupancy_offset = OG_MapBlock->getOffset("occupancy");
            off.biome_stuffs = OG_MapBlock->getOffset ("biome_stuffs");
            off.veinvector = OG_MapBlock->getOffset ("vein_vector");
            off.local_feature_offset = OG_MapBlock->getOffset ("feature_local");
            off.global_feature_offset = OG_MapBlock->getOffset ("feature_global");
            off.temperature1_offset = OG_MapBlock->getOffset ("temperature1");
            off.temperature2_offset = OG_MapBlock->getOffset ("temperature2");
        }
        try
        {
            off.mystery = OG_MapBlock->getOffset ("mystery_offset");
        }
        catch(Error::AllMemdef &)
        {
            off.mystery = 0;
        }
        try
        {
            OffsetGroup *OG_Geology = OG_Maps->getGroup("geology");
            if(d->usesWorldDataPtr)
            {
                off.world_regions =  OG_Geology->getOffset ("ptr2_region_array_from_wdata");
                off.world_geoblocks_vector =  OG_Geology->getOffset ("geoblock_vector_from_wdata");
            }
            else
            {
                off.world_regions =  OG_Geology->getAddress ("ptr2_region_array");
                off.world_geoblocks_vector =  OG_Geology->getAddress ("geoblock_vector");
            }
            off.region_size =  OG_Geology->getHexValue ("region_size");
            off.region_geo_index_offset =  OG_Geology->getOffset ("region_geo_index_off");
            off.geolayer_geoblock_offset = OG_Geology->getOffset ("geolayer_geoblock_offset");
            off.type_inside_geolayer = OG_Geology->getOffset ("type_inside_geolayer");
        }
        catch(Error::AllMemdef &)
        {
            d->hasGeology = false;
        }
        OffsetGroup *OG_global_features = OG_Maps->getGroup("features")->getGroup("global");
        OffsetGroup *OG_local_features = OG_Maps->getGroup("features")->getGroup("local");
        try
        {
            if(d->usesWorldDataPtr)
            {
                off.local_f_start = OG_local_features->getOffset("start_ptr_from_wdata");
                off.global_vector = OG_global_features->getOffset("vector_from_wdata");
            }
            else
            {
                off.local_f_start = OG_local_features->getAddress("start_ptr");
                off.global_vector = OG_global_features->getAddress("vector");
            }
            off.local_material = OG_local_features->getOffset("material");
            off.local_submaterial = OG_local_features->getOffset("submaterial");

            off.global_funcptr =  OG_global_features->getOffset("funcptr");
//.........这里部分代码省略.........
开发者ID:zilpin,项目名称:dfhack,代码行数:101,代码来源:Maps.cpp

示例9: SetValueIsValid

bool
ValueObjectVariable::UpdateValue ()
{
    SetValueIsValid (false);
    m_error.Clear();

    Variable *variable = m_variable_sp.get();
    DWARFExpression &expr = variable->LocationExpression();
    
    if (variable->GetLocationIsConstantValueData())
    {
        // expr doesn't contain DWARF bytes, it contains the constant variable
        // value bytes themselves...
        if (expr.GetExpressionData(m_data))
            m_value.SetContext(Value::eContextTypeVariable, variable);
        else
            m_error.SetErrorString ("empty constant data");
        // constant bytes can't be edited - sorry
        m_resolved_value.SetContext(Value::eContextTypeInvalid, NULL);
    }
    else
    {
        lldb::addr_t loclist_base_load_addr = LLDB_INVALID_ADDRESS;
        ExecutionContext exe_ctx (GetExecutionContextRef());
        
        Target *target = exe_ctx.GetTargetPtr();
        if (target)
        {
            m_data.SetByteOrder(target->GetArchitecture().GetByteOrder());
            m_data.SetAddressByteSize(target->GetArchitecture().GetAddressByteSize());
        }

        if (expr.IsLocationList())
        {
            SymbolContext sc;
            variable->CalculateSymbolContext (&sc);
            if (sc.function)
                loclist_base_load_addr = sc.function->GetAddressRange().GetBaseAddress().GetLoadAddress (target);
        }
        Value old_value(m_value);
        if (expr.Evaluate (&exe_ctx, NULL, NULL, NULL, loclist_base_load_addr, NULL, m_value, &m_error))
        {
            m_resolved_value = m_value;
            m_value.SetContext(Value::eContextTypeVariable, variable);
            
            ClangASTType clang_type = GetClangType();
            if (clang_type.IsValid())
                m_value.SetClangType(clang_type);

            Value::ValueType value_type = m_value.GetValueType();
            
            switch (value_type)
            {
                case Value::eValueTypeFileAddress:
                    SetAddressTypeOfChildren(eAddressTypeFile);
                    break;
                case Value::eValueTypeHostAddress:
                    SetAddressTypeOfChildren(eAddressTypeHost);
                    break;
                case Value::eValueTypeLoadAddress:
                case Value::eValueTypeScalar:
                case Value::eValueTypeVector:
                    SetAddressTypeOfChildren(eAddressTypeLoad);
                    break;
            }

            switch (value_type)
            {
            case Value::eValueTypeVector:
                    // fall through
            case Value::eValueTypeScalar:
                // The variable value is in the Scalar value inside the m_value.
                // We can point our m_data right to it.
                m_error = m_value.GetValueAsData (&exe_ctx, m_data, 0, GetModule().get());
                break;

            case Value::eValueTypeFileAddress:
            case Value::eValueTypeLoadAddress:
            case Value::eValueTypeHostAddress:
                // The DWARF expression result was an address in the inferior
                // process. If this variable is an aggregate type, we just need
                // the address as the main value as all child variable objects
                // will rely upon this location and add an offset and then read
                // their own values as needed. If this variable is a simple
                // type, we read all data for it into m_data.
                // Make sure this type has a value before we try and read it

                // If we have a file address, convert it to a load address if we can.
                Process *process = exe_ctx.GetProcessPtr();
                if (value_type == Value::eValueTypeFileAddress && process && process->IsAlive())
                {
                    lldb::addr_t file_addr = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
                    if (file_addr != LLDB_INVALID_ADDRESS)
                    {
                        SymbolContext var_sc;
                        variable->CalculateSymbolContext(&var_sc);
                        if (var_sc.module_sp)
                        {
                            ObjectFile *objfile = var_sc.module_sp->GetObjectFile();
                            if (objfile)
//.........这里部分代码省略.........
开发者ID:yongaru,项目名称:lldb,代码行数:101,代码来源:ValueObjectVariable.cpp

示例10: IsisMain

void IsisMain() {

  QString projName;

  Process pHist;
  Cube *icube = pHist.SetInputCube("FROM");

  // Check to see if the input cube looks like a HiRISE RDR
  if (icube->bandCount() > 3) {
    QString msg = "Input file [" +
                 Application::GetUserInterface().GetFileName("FROM") +
                 "] does not appear to be a HiRISE RDR product. Number of " +
                 "bands is greater than 3";
    throw IException(IException::Programmer, msg, _FILEINFO_);
  }

  // Setup to get a histogram for each band
  g_min = new double[icube->bandCount()];
  g_max = new double[icube->bandCount()];

  UserInterface &ui = Application::GetUserInterface();

  // Determine if the data is to be converted to JPEG2000
  IString enctype = ui.GetString("ENCODING_TYPE");
  enctype.DownCase();

  for (int band = 1; band <= icube->bandCount(); ++band) {

    if (ui.GetString("TYPE").compare("AUTOMATIC") == 0) {
      // Set up a histogram for this band. This call sets the input range
      // by making an initial stats pass to find the data min and max
      Histogram hist(*icube, band, pHist.Progress());

      // Loop and accumulate histogram
      pHist.Progress()->SetText("Gathering Histogram");
      pHist.Progress()->SetMaximumSteps(icube->lineCount());
      pHist.Progress()->CheckStatus();
      LineManager line(*icube);
      for (int i = 1; i <= icube->lineCount(); i++) {
        line.SetLine(i, band);
        icube->read(line);
        hist.AddData(line.DoubleBuffer(), line.size());
        pHist.Progress()->CheckStatus();
      }

      // get the requested cumulative percentages
      g_min[band-1] = ui.GetDouble("MINPER") == 0.0 ? hist.Minimum() : hist.Percent(ui.GetDouble("MINPER"));
      g_max[band-1] = ui.GetDouble("MAXPER") == 100.0 ? hist.Maximum() : hist.Percent(ui.GetDouble("MAXPER"));
    }
    else {
      g_min[band-1] = ui.GetDouble("MIN");
      g_max[band-1] = ui.GetDouble("MAX");
    }
  }

  // Find the minimum min and maximum max for all bands
  double minmin = g_min[0];
  double maxmax = g_max[0];
  for (int band = 1; band < icube->bandCount(); ++band) {
    if (g_min[band] < minmin) minmin = g_min[band];
    if (g_max[band] > maxmax) maxmax = g_max[band];
  }

  pHist.EndProcess();

  // Set up for writing the data to a PDS formatted file
  ProcessExportPds p;
  Cube *icube2 = p.SetInputCube("FROM");

  if (enctype.Equal("jp2")) {
    g_jp2buf = new char* [icube2->bandCount()];
    FileName lblFile(ui.GetFileName("TO"));
    QString lblFileName = lblFile.path() + "/" + lblFile.baseName() + ".lbl";
    p.SetDetached(lblFileName);
    p.setFormat(ProcessExport::JP2);
  }

  // Set the output pixel type and the special pixel values
  int nbits = ui.GetInteger("BITS");
  if (nbits == 8) {
    if (enctype.Equal("jp2")) {
      for (int i = 0; i < icube2->bandCount(); i++) {
        g_jp2buf[i] = new char[icube2->sampleCount()];
      }
    }
    g_oType = Isis::UnsignedByte;
    p.SetOutputType(g_oType);
    p.SetOutputRange(VALID_MIN1, VALID_MAX1);
    p.SetOutputNull(NULL1);
    p.SetOutputLis(LOW_INSTR_SAT1);
    p.SetOutputLrs(LOW_REPR_SAT1);
    p.SetOutputHis(HIGH_INSTR_SAT1);
    p.SetOutputHrs(HIGH_REPR_SAT1);
  }
  else if (nbits == 16) {
    if (enctype.Equal("jp2")) {
      for (int i = 0; i < icube2->bandCount(); i++) {
        g_jp2buf[i] = new char[icube2->sampleCount()*2];
      }
    }
//.........这里部分代码省略.........
开发者ID:jlaura,项目名称:isis3,代码行数:101,代码来源:hirdrgen.cpp

示例11: testClass

int testClass(const String& className, const int& attempt)
{
  Array<CIMObjectPath> refs;

  cout << endl << "+++++ Testing Class " << className << " +++++" << endl;

  // =======================================================================
  // enumerateInstanceNames
  // =======================================================================

  cout << "+++++ enumerateInstanceNames(" << className << "): ";
  try
  {
    refs = c.enumerateInstanceNames(NAMESPACE,className);
  }
  catch (Exception& e)
  {
    cout << endl;
    errorExit(e);
  }

  cout << refs.size() << " instances" << endl;

  // There must be at least 5 processes or something's wrong
  if (refs.size() < 5)
  {
    cout << "+++++ Error: too few instances returned" << endl;
    return 1;
  }

  // =======================================================================
  // getInstance
  // =======================================================================

  // -------------------- First do normal getInstance() --------------------

  // pick the middle instance of the bunch in the first attempt, or 
  // 1/4th or 1/8th of the list in second and third attempts respectively.
  
  Uint32 i = (refs.size()-1) 
      >> (attempt + 1);  // This is a shift right, not streamio!
  
  CIMObjectPath ref = refs[i];
  CIMInstance inst;
  cout << "+++++ getInstance " << i << endl;
  try
  {
    inst = c.getInstance(NAMESPACE,ref);
  }
  catch (Exception& e)
  {
    errorExit(e);
  }

  if (processTestVerbose)
  {
    // Display keys
    Array<CIMKeyBinding> keys = ref.getKeyBindings();
    cout << "  Keys:" << endl;
    for (i=0; i<keys.size(); i++)
      cout << "    " << keys[i].getName().getString() << " = " <<
          keys[i].getValue() << endl;
  }

  // check returned property values

  // first get the PID and load a process object
  String handle;
  inst.getProperty(inst.findProperty("handle")).getValue().get(handle);
  Process p;
  // error if can't get the process
  if (!p.findProcess(handle))
  {
    cout << "+++++ Error: can't find process corresponding to instance" << endl;
    return 1;
  }

  if (processTestVerbose) cout << "  Properties:" << endl;

  String sa, sb;
  Array<String> asa, asb;
  Uint16 i16a, i16b;
  Uint32 i32a, i32b;
  Uint64 i64a, i64b;
  CIMDateTime da, db;

  // For each property, get it from the just-loaded process
  // object and compare with what was returned by getInstance()

  // Caption and Description are common to all classes
  if (p.getCaption(sa))
  {
    if (processTestVerbose) cout << "    Caption" << endl;
    inst.getProperty(inst.findProperty("Caption")).getValue().get(sb);
    if (sa != sb)
    {
      cout << "+++++ Error: property mismatch: Caption" << endl;
      return 1;
    }
  }
//.........这里部分代码省略.........
开发者ID:deleisha,项目名称:neopegasus,代码行数:101,代码来源:TestProcessProvider.cpp

示例12: sys_ppoll

int sys_ppoll(struct pollfd* user_fds, size_t nfds,
              const struct timespec* user_timeout_ts,
              const sigset_t* user_sigmask)
{
	ioctx_t ctx; SetupKernelIOCtx(&ctx);

	struct timespec timeout_ts;
	if ( !FetchTimespec(&timeout_ts, user_timeout_ts) )
		return -1;

	if ( user_sigmask )
		return errno = ENOSYS, -1;

	struct pollfd* fds = CopyFdsFromUser(user_fds, nfds);
	if ( !fds ) { return -1; }

	PollNode* nodes = new PollNode[nfds];
	if ( !nodes ) { delete[] fds; return -1; }

	Process* process = CurrentProcess();

	kthread_mutex_t wakeup_mutex = KTHREAD_MUTEX_INITIALIZER;
	kthread_cond_t wakeup_cond = KTHREAD_COND_INITIALIZER;

	kthread_mutex_lock(&wakeup_mutex);

	int ret = -1;
	bool self_woken = false;
	bool remote_woken = false;
	bool unexpected_error = false;

	Timer timer;
	struct poll_timeout pts;
	if ( timespec_le(timespec_make(0, 1), timeout_ts) )
	{
		timer.Attach(Time::GetClock(CLOCK_MONOTONIC));
		struct itimerspec its;
		its.it_interval = timespec_nul();
		its.it_value = timeout_ts;
		pts.wake_mutex = &wakeup_mutex;
		pts.wake_cond = &wakeup_cond;
		pts.woken = &remote_woken;
		timer.Set(&its, NULL, 0, poll_timeout_callback, &pts);
	}

	size_t reqs;
	for ( reqs = 0; !unexpected_error && reqs < nfds; )
	{
		PollNode* node = nodes + reqs;
		if ( fds[reqs].fd < 0 )
		{
			fds[reqs].revents = POLLNVAL;
			// TODO: Should we set POLLNVAL in node->revents too? Should this
			// system call ignore this error and keep polling, or return to
			// user-space immediately? What if conditions are already true on
			// some of the file descriptors (those we have processed so far?)?
			node->revents = 0;
			reqs++;
			continue;
		}
		Ref<Descriptor> desc = process->GetDescriptor(fds[reqs].fd);
		if ( !desc ) { self_woken = unexpected_error = true; break; }
		node->events = fds[reqs].events | POLL__ONLY_REVENTS;
		node->revents = 0;
		node->wake_mutex = &wakeup_mutex;
		node->wake_cond = &wakeup_cond;
		node->woken = &remote_woken;
		reqs++;
		// TODO: How should errors be handled?
		if ( desc->poll(&ctx, node) == 0 )
			self_woken = true;
		else if ( errno == EAGAIN )
			errno = 0;
		else
			unexpected_error = self_woken = true;
	}

	if ( timeout_ts.tv_sec == 0 && timeout_ts.tv_nsec == 0 )
		self_woken = true;

	while ( !(self_woken || remote_woken) )
	{
		if ( !kthread_cond_wait_signal(&wakeup_cond, &wakeup_mutex) )
			errno = -EINTR,
			self_woken = true;
	}

	kthread_mutex_unlock(&wakeup_mutex);

	for ( size_t i = 0; i < reqs; i++ )
		if ( 0 <= fds[i].fd )
			nodes[i].Cancel();

	if ( timespec_le(timespec_make(0, 1), timeout_ts) )
	{
		timer.Cancel();
		timer.Detach();
	}

	if ( !unexpected_error )
//.........这里部分代码省略.........
开发者ID:amanuel2,项目名称:IMPORTED_OS_MIRROR,代码行数:101,代码来源:poll.cpp

示例13: NODE_IMPLEMENTATION

NODE_IMPLEMENTATION(DynamicPartialApplication::node, Pointer)
{
    //
    //  Never do partial application on the result of a lambda
    //  expression (its too difficult to archive). Instead do
    //  partial evaluation. The good side is that there will never
    //  be more than one level of indirection in multiple-curried
    //  lambda expressions. the bad side is that there will be
    //  more overhead upfront.
    //

    Process* p = NODE_THREAD.process();
    Context* c = p->context();
    FunctionObject* f = NODE_ARG_OBJECT(1, FunctionObject);
    bool apply = f->function()->isLambda();

    try
    {
        if (apply)
        {
            typedef PartialApplicator Generator;
            Generator::ArgumentVector args(f->function()->numArgs() +
                                           f->function()->numFreeVariables());
            Generator::ArgumentMask   mask(args.size());

            for (int i=0; i < args.size(); i++)
            {
                mask[i] = NODE_THIS.argNode(i+2)->symbol() != c->noop();
                if (mask[i])
                {
                    args[i] = NODE_ANY_TYPE_ARG(i+2);
                }
            }

            Generator evaluator(f->function(), p, &NODE_THREAD, args, mask);

            const FunctionType* rt = evaluator.result()->type();
            assert(rt == NODE_THIS.argNode(0)->type());
            FunctionObject* o = new FunctionObject(rt);
            o->setDependent(f);
            o->setFunction(evaluator.result());
            NODE_RETURN(Pointer(o));
        }
        else
        {
            typedef FunctionSpecializer Generator;
            Generator::ArgumentVector args(f->function()->numArgs() +
                                           f->function()->numFreeVariables());
            Generator::ArgumentMask   mask(args.size());

            for (int i=0; i < args.size(); i++)
            {
                mask[i] = NODE_THIS.argNode(i+2)->symbol() != c->noop();

                if (mask[i])
                {
                    args[i] = NODE_ANY_TYPE_ARG(i+2);
                }
            }

            Generator evaluator(f->function(), p, &NODE_THREAD);
            evaluator.partiallyEvaluate(args, mask);

            const FunctionType* rt = evaluator.result()->type();
            assert(rt == NODE_THIS.argNode(0)->type());
            FunctionObject* o = new FunctionObject(rt);
            o->setFunction(evaluator.result());
            NODE_RETURN(Pointer(o));
        }
    }
    catch (Exception& e)
    {
        ProgramException exc(NODE_THREAD);
        exc.message() = e.message();
        exc.message() += " during partial ";
        exc.message() += (apply ? "application" : "evaluation");
        exc.message() += " of ";
        exc.message() += f->function()->name().c_str();
        throw exc;
    }
}
开发者ID:jimhourihan,项目名称:mu,代码行数:81,代码来源:BaseFunctions.cpp

示例14: ReceiveStateFromParticipant

void* ReceiveStateFromParticipant(void* _rcv_thread_arg) {
    ReceiveStateThreadArgument *rcv_thread_arg = (ReceiveStateThreadArgument *)_rcv_thread_arg;
    int pid = rcv_thread_arg->pid;
    int tid = rcv_thread_arg->transaction_id;
    Process *p = rcv_thread_arg->p;
    char buf[kMaxDataSize];
    int num_bytes;
    //TODO: write code to extract multiple messages

    fd_set temp_set;
    FD_ZERO(&temp_set);
    FD_SET(p->get_fd(pid), &temp_set);
    int fd_max = p->get_fd(pid);
    int rv;
    rv = select(fd_max + 1, &temp_set, NULL, NULL, (timeval*)&kTimeout);
    if (rv == -1) { //error in select
        // cout << "P" << p->get_pid() << ": ERROR in select() for P" << pid << strerror(errno)<< endl;
        rcv_thread_arg->st = PROCESSTIMEOUT;
        p->RemoveFromUpSet(pid);
    } else if (rv == 0) {   //timeout
        rcv_thread_arg->st = PROCESSTIMEOUT;
        p->RemoveFromUpSet(pid);
    } else {    // activity happened on the socket
        if ((num_bytes = recv(p->get_fd(pid), buf, kMaxDataSize - 1, 0)) == -1) {
            // cout << "P" << p->get_pid() << ": ERROR in receiving for P" << pid << endl;
            rcv_thread_arg->st = PROCESSTIMEOUT;
            p->RemoveFromUpSet(pid);
        } else if (num_bytes == 0) {     //connection closed
            // cout << "P" << p->get_pid() << ": Connection closed by P" << pid << endl;
            // if participant closes connection, it is equivalent to it crashing
            // can treat it as TIMEOUT
            // TODO: verify argument
            rcv_thread_arg->st = PROCESSTIMEOUT;
            p->RemoveFromUpSet(pid);
            //TODO: handle connection close based on different cases
        } else {
            buf[num_bytes] = '\0';
            cout << "P" << p->get_pid() << ": STATE received from P" << pid << ": " << buf <<  endl;

            string extracted_msg;
            int received_tid;
            // in this case, we don't care about the received_tid,
            // because it will surely be for the transaction under consideration
            p->ExtractMsg(string(buf), extracted_msg, received_tid);

            ProcessState msg = static_cast<ProcessState>(atoi(extracted_msg.c_str()));
            rcv_thread_arg->st = msg;
            //assumes that correct message type is sent by participant

            // if (msg==)  {    // it's a YES
            //     received_msg_type = YES;
            // } else if (extracted_msg == msg2) { // it's a NO
            //     received_msg_type = NO;
            // } else {
            //     //TODO: take actions appropriately, like check log for previous transaction decision.
            //     cout << "P" << p->get_pid() << ": Unexpected msg received from P" << pid << endl;
            //     received_msg_type = ERROR;
            // }
        }
    }
    // cout << "P" << p->get_pid() << ": Receive thread exiting for P" << pid << endl;
    return NULL;
}
开发者ID:shobhit6993,项目名称:3-phase-commit,代码行数:63,代码来源:coordinator.cpp

示例15: NewCoordinatorMode

void* NewCoordinatorMode(void * _p) {
    //TODO: send tid to ConstructVoteReq;
    Process *p = (Process *)_p;
    ofstream outf("log/newcoord" + to_string(p->get_pid()) + "," + to_string(time(NULL) % 100), fstream::app);
    outf << "New Coordinator = " << p->get_pid() << endl;

    // connect to each participant
    p->participant_state_map_.clear();
    //set participant state map but only those processes that are alive
    for (auto it = p->up_.begin(); it != p->up_.end(); it++) {
        if (*it == p->get_pid()) continue;
        if (p->ConnectToProcess(*it))
            p->participant_state_map_.insert(make_pair(*it, UNINITIALIZED));
        // else
        // cout << "P" << p->get_pid() << ": Unable to connect to P" << *it << endl;
    }
    // return NULL;
    string msg;
    p->ConstructStateReq(msg);

    p->SendStateReqToAll(msg);
    outf << "sent state req" << endl;
    p->WaitForStates();
    ProcessState my_st = p->get_my_state();

    // if(p->get_pid() == 1) return NULL;

    bool aborted = false;
    for (const auto& ps : p->participant_state_map_) {
        if (ps.second == ABORTED)
        {
            aborted = true;
            break;
        }
    }

    if (my_st == ABORTED || aborted)
    {
        if (my_st != ABORTED)
        {
            p->LogAbort();
            //only log if other process is abort.
            //if i know aborted, means already in log abort
            my_st = ABORTED;

        }

        for (const auto& ps : p->participant_state_map_) {
            p->SendAbortToProcess(ps.first);
        }
        p->set_my_state(ABORTED);
        p->RemoveThreadFromSet(pthread_self());
        return NULL;
    }

    bool committed = false;
    for (const auto& ps : p->participant_state_map_) {
        if (ps.second == COMMITTED)
        {
            committed = true;
            break;
        }
    }

    if (my_st == COMMITTED || committed)
    {
        if (my_st != COMMITTED)
        {
            p->LogCommit();
            my_st = COMMITTED;
        }
        p->SendCommitToAll();
        p->set_my_state(COMMITTED);
        p->RemoveThreadFromSet(pthread_self());
        return NULL;
    }


    bool uncert = true;
    for (const auto& ps : p->participant_state_map_) {
        if (ps.second == PROCESSTIMEOUT)continue;
        if (ps.second != UNCERTAIN)
        {
            uncert = false;
            break;
        }
    }
    if (uncert && my_st == UNCERTAIN)
    {
        outf << "sending abort" << endl;
        p->LogAbort();
        for (const auto& ps : p->participant_state_map_) {
            p->SendAbortToProcess(ps.first);
        }
        p->set_my_state(ABORTED);
        p->RemoveThreadFromSet(pthread_self());
        return NULL;
    }

    //else
//.........这里部分代码省略.........
开发者ID:shobhit6993,项目名称:3-phase-commit,代码行数:101,代码来源:coordinator.cpp


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