コード例 #1
0
void test_get_bloccante_buffer_vuoto(void) {

    pthread_t cons;

    buffer buf = allocBuffer(1);

    void *messaggio = (void *) 32;

    numero_consumatori_attivi = 1;

    pthread_create(&cons, NULL, &consumatore_bloccante_c1, buf);

    putInBuffer_blocking(buf, messaggio);

    pthread_join(cons, NULL);

    CU_ASSERT_EQUAL(numero_consumatori_attivi, 0);

    CU_ASSERT_PTR_EQUAL(buf->list_cell_full->buffer_cell_head, NULL);

    freeBuffer(buf);
}
コード例 #2
0
/*--------------------------------------------------------------------
 * DESCRIPTION	(Private -- phase out 5/4/95)
 *	Set the name of the file to associate with the profile.
 *	If the Name is NULL no file will be associated with the profile.
 *
 * AUTHOR
 * 	lsh
 *
 * DATE CREATED
 *	Octorber 22, 1993
 *------------------------------------------------------------------*/
SpStatus_t KSPAPI SpProfileSetFileName (
    SpProfile_t		Profile,
    char			FAR *FileName)
{
    char			FAR *fileName;
    SpProfileData_t	FAR *ProfileData;

    /* convert profile handle to data pointer */
    ProfileData = SpProfileLock (Profile);
    if (NULL == ProfileData)
        return SpStatBadProfile;

    /* Free current FileName if one is there */
    if (ProfileData->FileName != NULL)
        freeBuffer(ProfileData->FileName);

    /* create the FileName handle */
    ProfileData->FileName = allocBufferHandle (strlen (FileName) + 1);
    if (ProfileData->FileName == NULL)
        return (SpStatMemory);

    /* lock FileName handle and return ptr */
    fileName = (char *) lockBuffer (ProfileData->FileName);
    if (fileName == NULL)
        return (SpStatMemory);

    /* copy text data into the newly allocated space */
    strcpy (fileName, FileName);

#if defined (KPMAC)
    SpProfileClearProps(&(ProfileData->Props));
#endif

    /* unlock handles */
    unlockBuffer (ProfileData->FileName);
    SpProfileUnlock (Profile);
    return SpStatSuccess;
}
コード例 #3
0
    void GL3PlusHardwarePixelBuffer::blitFromMemory(const PixelBox &src, const Box &dstBox)
    {
        if (!mBuffer.contains(dstBox))
        {
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
                        "Destination box out of range",
                        "GL3PlusHardwarePixelBuffer::blitFromMemory");
        }

        PixelBox scaled;

        if (src.getWidth() != dstBox.getWidth() ||
            src.getHeight() != dstBox.getHeight() ||
            src.getDepth() != dstBox.getDepth())
        {
            // Scale to destination size.
            // This also does pixel format conversion if needed.
            allocateBuffer();
            scaled = mBuffer.getSubVolume(dstBox);
            Image::scale(src, scaled, Image::FILTER_BILINEAR);
        }
        else if (GL3PlusPixelUtil::getGLInternalFormat(src.format) == 0)
        {
            // Extents match, but format is not accepted as valid
            // source format for GL. Do conversion in temporary buffer.
            allocateBuffer();
            scaled = mBuffer.getSubVolume(dstBox);
            PixelUtil::bulkPixelConversion(src, scaled);
        }
        else
        {
            // No scaling or conversion needed.
            scaled = src;
        }

        upload(scaled, dstBox);
        freeBuffer();
    }
コード例 #4
0
/* 
 * Compute 2D DFT on double data:
 * forward if direction==FFT_FORWARD,
 * inverse if direction==FFT_INVERSE.
 */
int fft2d(DCOMPLEX *array, int rows, int cols, int direction)
{
  int i, maxsize, errflag;
  
  if(!power_of_2(rows) || !power_of_2(cols)) {
    handle_error("fft: input array must have dimensions a power of 2");
    return(ERROR);
  }
  
  /* Allocate 1D buffer */
  bigBuffd = array;
  maxsize = rows>cols ? rows : cols;
  errflag = allocateBuffer(maxsize);
  if(errflag != NO_ERROR) return(errflag);

  /* Compute transform row by row */
  if(cols>1)
    for(i=0;i<rows;i++) 
      {
      	LoadRow(bigBuffd,i,cols);
      	FFT842(direction,cols,stageBuff);
      	StoreRow(bigBuffd,i,cols);
      }
  
  /* Compute transform column by column */
  if(rows>1)
    for(i=0;i<cols;i++) 
      {
        LoadCol(bigBuffd,i,rows,cols);
        FFT842(direction,rows,stageBuff);
        StoreCol(bigBuffd,i,rows,cols);
      }

  freeBuffer();
  return(NO_ERROR);
}
コード例 #5
0
void TGroup::setState(ushort aState, Boolean enable) {
   setBlock sb;
   sb.st = aState;
   sb.en = enable;

   TView::setState(aState, enable);

   if ((aState & (sfActive | sfDragging)) != 0) {
      lock();
      forEach(doSetState, &sb);
      unlock();
   }

   if ((aState & sfFocused) != 0) {
      if (current != 0)
         current->setState(sfFocused, enable);
   }

   if ((aState & sfExposed) != 0) {
      forEach(doExpose, &enable);
      if (enable == False)
         freeBuffer();
   }
}
コード例 #6
0
ファイル: ne_sspi.c プロジェクト: CyberShadow/Far-NetBox
/*
 * Processes received authentication tokens as well as supplies the
 * response token.
 */
int ne_sspi_authenticate(void *context, const char *base64Token, char **responseToken)
{
    SecBufferDesc outBufferDesc;
    SecBuffer outBuffer;
    int status;
    SECURITY_STATUS securityStatus;
    ULONG contextFlags;

    SSPIContext *sspiContext;
    if (initialized <= 0) {
        return -1;
    }

    status = getContext(context, &sspiContext);
    if (status) {
        return status;
    }

    /* TODO: Not sure what flags should be set. joe: this needs to be
     * driven by the ne_auth interface; the GSSAPI code needs similar
     * flags. */
    contextFlags = ISC_REQ_CONFIDENTIALITY | ISC_REQ_MUTUAL_AUTH;

    initSingleEmptyBuffer(&outBufferDesc, &outBuffer);
    status = makeBuffer(&outBufferDesc, sspiContext->maxTokenSize);
    if (status) {
        return status;
    }

    if (base64Token) {
        SecBufferDesc inBufferDesc;
        SecBuffer inBuffer;

        if (!sspiContext->continueNeeded) {
            freeBuffer(&outBufferDesc);
            NE_DEBUG(NE_DBG_HTTPAUTH, "sspi: Got an unexpected token.\n");
            return -1;
        }

        initSingleEmptyBuffer(&inBufferDesc, &inBuffer);

        status = base64ToBuffer(base64Token, &inBufferDesc);
        if (status) {
            freeBuffer(&outBufferDesc);
            return status;
        }

        securityStatus =
            initializeSecurityContext(&sspiContext->credentials,
                                      &(sspiContext->context),
                                      sspiContext->serverName, contextFlags,
                                      &inBufferDesc, &(sspiContext->context),
                                      &outBufferDesc);
        if (securityStatus == SEC_E_OK)
        {
            sspiContext->authfinished = 1;
        }
        freeBuffer(&inBufferDesc);
    } else {
        if (sspiContext->continueNeeded) {
            freeBuffer(&outBufferDesc);
            NE_DEBUG(NE_DBG_HTTPAUTH, "sspi: Expected a token from server.\n");
            return -1;
        }
        if (sspiContext->authfinished && (sspiContext->credentials.dwLower || sspiContext->credentials.dwUpper)) {
            if (sspiContext->authfinished)
            {
                freeBuffer(&outBufferDesc);
                sspiContext->authfinished = 0;
                NE_DEBUG(NE_DBG_HTTPAUTH,"sspi: failing because starting over from failed try.\n");
                return -1;
            }
            sspiContext->authfinished = 0;
        }

        /* Reset any existing context since we are starting over */
        resetContext(sspiContext);

        if (acquireCredentialsHandle
            (&sspiContext->credentials, sspiContext->mechanism) != SEC_E_OK) {
                freeBuffer(&outBufferDesc);
                NE_DEBUG(NE_DBG_HTTPAUTH,
                    "sspi: acquireCredentialsHandle failed.\n");
                return -1;
        }

        securityStatus =
            initializeSecurityContext(&sspiContext->credentials, NULL,
                                      sspiContext->serverName, contextFlags,
                                      NULL, &(sspiContext->context),
                                      &outBufferDesc);
    }

    if (securityStatus == SEC_I_COMPLETE_AND_CONTINUE
        || securityStatus == SEC_I_COMPLETE_NEEDED) {
        SECURITY_STATUS compleStatus =
            pSFT->CompleteAuthToken(&(sspiContext->context), &outBufferDesc);

        if (compleStatus != SEC_E_OK) {
            freeBuffer(&outBufferDesc);
            NE_DEBUG(NE_DBG_HTTPAUTH, "sspi: CompleteAuthToken failed.\n");
            return -1;
        }
    }

    if (securityStatus == SEC_I_COMPLETE_AND_CONTINUE
        || securityStatus == SEC_I_CONTINUE_NEEDED) {
        sspiContext->continueNeeded = 1;
    } else {
        sspiContext->continueNeeded = 0;
    }

    if (!(securityStatus == SEC_I_COMPLETE_AND_CONTINUE
          || securityStatus == SEC_I_COMPLETE_NEEDED
          || securityStatus == SEC_I_CONTINUE_NEEDED
          || securityStatus == SEC_E_OK)) {
        NE_DEBUG(NE_DBG_HTTPAUTH,
                 "sspi: initializeSecurityContext [failed] [%x].\n",
                 securityStatus);
        freeBuffer(&outBufferDesc);
        return -1;
    }

    *responseToken = ne_base64(outBufferDesc.pBuffers->pvBuffer,
                               outBufferDesc.pBuffers->cbBuffer);
    freeBuffer(&outBufferDesc);

    return 0;
}
コード例 #7
0
void freeSysBuffer (KpHandle_t handle)
{
       freeBuffer (handle);
}
コード例 #8
0
ファイル: MemoryManager.cpp プロジェクト: 0x7d/cameraCodes
/*--------------------MemoryManager Class STARTS here-----------------------------*/
void* MemoryManager::allocateBuffer(int width, int height, const char* format,
		int &bytes, int numBufs) {
	LOG_FUNCTION_NAME;

	if (mIonFd == 0) {
		mIonFd = ion_open();
		if (mIonFd == 0) {
			LOGE("ion_open failed!!!");
			return NULL;
		}
	}

	///We allocate numBufs+1 because the last entry will be marked NULL to indicate end of array, which is used when freeing
	///the buffers
	const uint numArrayEntriesC = (uint)(numBufs + 1);

	///Allocate a buffer array
	uint32_t *bufsArr = new uint32_t[numArrayEntriesC];
	if (!bufsArr) {
		LOGE(
				"Allocation failed when creating buffers array of %d uint32_t elements",
				numArrayEntriesC);
		LOG_FUNCTION_NAME_EXIT;
		return NULL;
	}

	///Initialize the array with zeros - this will help us while freeing the array in case of error
	///If a value of an array element is NULL, it means we didnt allocate it
	memset(bufsArr, 0, sizeof(*bufsArr) * numArrayEntriesC);

	//2D Allocations are not supported currently
	if (bytes != 0) {
		struct ion_handle *handle;
		int mmap_fd;

		///1D buffers
		for (int i = 0; i < numBufs; i++) {
			int ret = ion_alloc(mIonFd, bytes, 0, 1 << ION_HEAP_TYPE_CARVEOUT,
					&handle);
			if (ret < 0) {
				LOGE("ion_alloc resulted in error %d", ret);
				goto error;
			}

			LOGE("Before mapping, handle = %x, nSize = %d", handle, bytes);
			if ((ret = ion_map(mIonFd, handle, bytes, PROT_READ | PROT_WRITE,
					MAP_SHARED, 0, (unsigned char**) &bufsArr[i], &mmap_fd))
					< 0) {
				LOGE("Userspace mapping of ION buffers returned error %d", ret);
				ion_free(mIonFd, handle);
				goto error;
			}

			mIonHandleMap.add(bufsArr[i], (unsigned int) handle);
			mIonFdMap.add(bufsArr[i], (unsigned int) mmap_fd);
			mIonBufLength.add(bufsArr[i], (unsigned int) bytes);
		}

	} else // If bytes is not zero, then it is a 2-D tiler buffer request
	{
	}

	LOG_FUNCTION_NAME_EXIT;

	return (void*) bufsArr;

	error: LOGE("Freeing buffers already allocated after error occurred");
	freeBuffer(bufsArr);

	if (NULL != mErrorNotifier.get()) {
		mErrorNotifier->errorNotify(-ENOMEM);
	}

	LOG_FUNCTION_NAME_EXIT;
	return NULL;
}
コード例 #9
0
ファイル: cmd_post.c プロジェクト: colin-dvlp/chinamobile
BOOL  trans_upload_file(iclock_options_t *opt,data_list_t*CurrentNode,int mode)
{
	char url[1024];
	char buf[1024];
	char str_temp[512];
	int c = -1;
	int file_index;
	trans_info_t info;
	int fd;
	char file_name[128];
	int file_offset;
	int read_data_len = 0;
	int trans_help_fp;
	BOOL  ret = TRUE;

	if (CurrentNode == NULL || opt == NULL) {
		return TRUE;
	}
	chmod(BS_TRANS_HELP_FILE,0666);
	trans_help_fp = open(BS_TRANS_HELP_FILE,O_RDWR|O_NONBLOCK);
	file_offset = get_file_info(CurrentNode->con_type,mode,file_name);
	if (trans_help_fp < 0) {
		return TRUE;
	}
	if (file_offset < 0) {
		close(trans_help_fp);
		return TRUE;
	}
	if ((!read_file_with_offset(trans_help_fp,file_offset,(char *)&file_index,sizeof(file_index)))
		|| (file_index < 0)) {	
		close(trans_help_fp);
		return TRUE;
	}
	memset(&info,0,sizeof(info));
	sprintf(str_temp,"gTransFlag=%s",opt->svr_trans_flag);
	info.cache = createRamBuffer(opt->buf_size);
	info.opt = opt;
	info.list = CurrentNode;
	read_file_with_offset(trans_help_fp, file_offset+sizeof(file_index),\
						(char *)&info.cur_trans_log_time,sizeof(info.cur_trans_log_time));
       info.starting_time = (size_t)OldEncodeTime(localtime(&info.cur_trans_log_time));
	opt->con_type = CurrentNode->con_type;
	url_init(opt,url,"OPERLOG");
	info.url = url;
	info.upload_mode = UPLOADE_MODE_QUERY;
	CurrentNode->param = str_temp;
	fd = open(file_name,O_RDWR|O_NONBLOCK);
	
	if ((fd >= 0) && (file_index >= 0) && (opt->main_fun->upload_usr_read_fun != NULL)) {
		if (svr_is_need_contype(opt->svr_trans_flag,CurrentNode->con_type)) {
			while ((read_data_len = opt->main_fun->upload_usr_read_fun(\
										CurrentNode->con_type,buf,file_index,fd)) > 0) {
				c = trans_user_all_data(buf,&info,str_temp,FCT_USER);
				if ( info.error != 0 || (c < 0)) {
					break;
				} 
				c = trans_user_all_data(buf,&info,str_temp,FCT_USERPIC);
				if ( info.error != 0 || (c < 0)) {
					break;
				} 
				c = trans_user_all_data(buf,&info,str_temp,FCT_FACE);
				if ( info.error != 0 || (c < 0)) {
					break;
				} 
				c = trans_user_all_data(buf,&info,str_temp,FCT_FINGERTMP);
				if ( info.error != 0 || (c < 0)) {
					break;
				} 
				if (( info.error == 0) && (info.count == 0) && (c > 0)) {
					write_file_with_offset(trans_help_fp,file_offset,(char *)&file_index,sizeof(int));
				}
				file_index += read_data_len;
			}
			if (( info.error == 0) && (info.count > 0) && (c >= 0)) {
				snprintf(info.url+strlen(info.url),sizeof(url)-strlen(info.url), "%u",(unsigned int)info.starting_time);
				if (cache_data_to_svr(url, &info)) {
					write_file_with_offset(trans_help_fp,file_offset,(char *)&file_index,sizeof(int));	
				}	
			}
		}
		if (read_data_len <  1) {
			file_index  = -1;
			write_file_with_offset(trans_help_fp,file_offset,(char *)&file_index,sizeof(int));	
			if (fd > 0) {
				close(fd);
			}
			fd = open(file_name, O_RDWR|O_CREAT|O_TRUNC|O_SYNC);
		}
		ret =  (read_data_len < 1);
	} else {
		ret = TRUE;
	}
	freeBuffer(info.cache);
	if (fd >= 0) {
		close(fd);
	}
	if (trans_help_fp >= 0) {
		close(trans_help_fp);
	}
	
	return ret;
}
コード例 #10
0
ファイル: file.c プロジェクト: openSUSE/fillup
/*-------------------- readFile --------------------*/
File_t
readFile 
(
    ParameterSpecification_t    fileSpecifier, /* in */
    const char                * filename       /* in */
)
{
    File_t                      returnValue;
    FILE                      * filePointer;
    long                        fileLength;

    if( FileOpened == openFileForReading( filename, &filePointer ) )
    {
        if( Success == getFileLength( filePointer, &fileLength ) )
        {
            void              * ptr;

            /*
             * Allocate one byte more if a newline must be added
             */
            if( Success == allocateBuffer( fileLength + 1 , &ptr ) )
            {
                char          * buffer = ( char * )ptr;

                if( Success == readFileToBuffer( filePointer, fileLength, &buffer ) )
                {

                    if ( FALSE == queryParameter( IgnoreEOF ) )
                    {
                        char  * eof = (buffer + fileLength - 1);

                        if ( *eof != '\n' )
                        {
                            *( eof + 1 ) = '\n';
                            fileLength++;
                        }
                    }

                    addToWatchdog( fileLength );
                    associateBuffer( fileSpecifier, fileLength, &buffer );
                    returnValue = FileOperationsSuccessful;
                }
                else
                {
                    freeBuffer( &buffer );
                    returnValue = FileOperationsFailed;
                }
            }
            else
            {
                returnValue = FileOperationsFailed;
            }
        }
        else
        {
            returnValue = FileOperationsFailed;
        }
        closeFile( filePointer );
    }
    else
    {
        returnValue = FileOperationsFailed;
    }

    return( returnValue );
}
コード例 #11
0
void* bridgeThread(void* arg)
{
  int remoteSocket = (int)(intptr_t) arg;
  
  if(0 != geteuid()) // run only as non-root
    {
      char* localPort = pGetConfig()->sslPort;
      char* localHost = pGetConfig()->sslHostname;
      struct timeval sshDetectTimeout = { pGetConfig()->timeOut , 0 }; // 2 sec
      struct timeval sslConnectionTimeout = { 120, 0 }; // 120 sec
      struct timeval connectionTimeout = { 7200,0 }; // 2 hours
      fd_set readFds;
      int rc;
		
      // test for ssl/ssh connection
      FD_ZERO(&readFds);
      FD_SET(remoteSocket, &readFds);
      rc = select(remoteSocket+1, &readFds, 0, 0, &sshDetectTimeout);
		
      if(rc != -1)
	{
	  struct addrinfo* addrInfo;
	  struct addrinfo* addrInfoBase;
	  int localSocket;
	  char prefetchBuffer[3];
	  ssize_t prefetchReadCount = 0;
	  	
	  if(rc == 0) // timeout -> ssh connection
	    {
	      localPort = pGetConfig()->sshPort;
	      localHost = pGetConfig()->sshHostname;
	    }
	  else	// ssl and SSH protocol 2 connections 
	    {
		  prefetchReadCount = recv(remoteSocket, prefetchBuffer, sizeof(prefetchBuffer), 0);
		  
		  if(memcmp("SSH",prefetchBuffer, sizeof(prefetchBuffer)) == 0)
		  {
			syslog(LOG_DEBUG,
				"%s(): incomming SSH protocol 2 connection detected ...",
				__FUNCTION__);
			  localPort = pGetConfig()->sshPort;
		          localHost = pGetConfig()->sshHostname;
		  }
		  else
		  {
			connectionTimeout.tv_sec= sslConnectionTimeout.tv_sec;
		  }
	    }
		  
	  resolvAddress(localHost, localPort, &addrInfo);

	  addrInfoBase = addrInfo; // need for delete

	  while(addrInfo != NULL)
          {
	      localSocket = socket(addrInfo->ai_family,
				   addrInfo->ai_socktype,
				   addrInfo->ai_protocol);
			
	      if(localSocket >= 0)
		{

	      		if(connect(localSocket,
				 addrInfo->ai_addr,
			 	addrInfo->ai_addrlen) != -1)
	       			break;
			else
	      			close(localSocket);
		}
		addrInfo = addrInfo->ai_next;
	  }
	
	  if(addrInfoBase != NULL)
          	freeaddrinfo(addrInfoBase);
   	
	  if (addrInfo != NULL)               /* address succeeded */
	    {
              struct bufferList_t* pBufferListElement = allocBuffer();
      
              // test Buffer
	      if(NULL != pBufferListElement &&
		 NULL !=  pBufferListElement->buffer)
              { 
              		if(rc != 0) // no timeout
			{
				if(writeall(localSocket, prefetchBuffer, prefetchReadCount) &&
					redirectData(remoteSocket, localSocket, pBufferListElement->buffer) > 0)
		    		{
		      			rc = 0; // handle as normal connection
		    		}
			}
		
	      		if(rc == 0)
			{  
	      			bridgeConnection(remoteSocket, localSocket,
				       pBufferListElement->buffer, &connectionTimeout);
                	}

	      		close(localSocket);

	      		freeBuffer(pBufferListElement);
	     }
	     else // invalid Buffer Structure
	     {
			syslog(LOG_ERR, "%s(): invalid Bufferpointer", __FUNCTION__);
	     }
	    }
	  else
	    {
		perror("unable to establish the client connection");
	    }
	}	
    }
  else
    {
      syslog(LOG_ERR,
	      "%s() threads running only as non-root", __FUNCTION__);
    }

  close(remoteSocket);
  modifyClientThreadCounter(-1);

  return NULL; // no receiver for return code
}
コード例 #12
0
 ~free_on_scope_exit() { if(!my_p) return; my_p->~T(); freeBuffer(my_p); }
コード例 #13
0
void run_lambdas_test( mode_array *filter_type ) {
    tbb::atomic<int> counter;
    counter = max_counter;
    // Construct filters using lambda-syntax and create the sequence when parallel_pipeline() is being run;
    resetCounters();  // only need the output_counter reset.
    tbb::parallel_pipeline( n_tokens,
        tbb::make_filter<void, t1>(filter_type[0], [&counter]( tbb::flow_control& control ) -> t1 {
                if( --counter < 0 )
                    control.stop();
                return t1(); }
        ) &
        tbb::make_filter<t1, t2>(filter_type[1], []( t1 /*my_storage*/ ) -> t2 {
                return t2(); }
        ) &
        tbb::make_filter<t2, void>(filter_type[2], [] ( t2 ) -> void {
                output_counter++; }
        )
    );
    checkCounters(no_pointer_counts);  // don't have to worry about specializations
    counter = max_counter;
    // pointer filters
    resetCounters();
    tbb::parallel_pipeline( n_tokens,
        tbb::make_filter<void, t1*>(filter_type[0], [&counter]( tbb::flow_control& control ) -> t1* {
                if( --counter < 0 ) {
                    control.stop();
                    return NULL;
                }
                return new(fetchNextBuffer()) t1(); }
        ) &
        tbb::make_filter<t1*, t2*>(filter_type[1], []( t1* my_storage ) -> t2* {
                tbb::tbb_allocator<t1>().destroy(my_storage); // my_storage->~t1();
                return new(my_storage) t2(); }
        ) &
        tbb::make_filter<t2*, void>(filter_type[2], [] ( t2* my_storage ) -> void {
                tbb::tbb_allocator<t2>().destroy(my_storage);  // my_storage->~t2();
                freeBuffer(my_storage);
                output_counter++; }
        )
    );
    checkCounters(no_pointer_counts);
    // first filter outputs pointer
    counter = max_counter;
    resetCounters();
    tbb::parallel_pipeline( n_tokens,
        tbb::make_filter<void, t1*>(filter_type[0], [&counter]( tbb::flow_control& control ) -> t1* {
                if( --counter < 0 ) {
                    control.stop();
                    return NULL;
                }
                return new(fetchNextBuffer()) t1(); }
        ) &
        tbb::make_filter<t1*, t2>(filter_type[1], []( t1* my_storage ) -> t2 {
                tbb::tbb_allocator<t1>().destroy(my_storage);   // my_storage->~t1();
                freeBuffer(my_storage);
                return t2(); }
        ) &
        tbb::make_filter<t2, void>(filter_type[2], [] ( t2 /*my_storage*/) -> void {
                output_counter++; }
        )
    );
    checkCounters(no_pointer_counts);
    // second filter outputs pointer
    counter = max_counter;
    resetCounters();
    tbb::parallel_pipeline( n_tokens,
        tbb::make_filter<void, t1>(filter_type[0], [&counter]( tbb::flow_control& control ) -> t1 {
                if( --counter < 0 ) {
                    control.stop();
                }
                return t1(); }
        ) &
        tbb::make_filter<t1, t2*>(filter_type[1], []( t1 /*my_storage*/ ) -> t2* {
                return new(fetchNextBuffer()) t2(); }
        ) &
        tbb::make_filter<t2*, void>(filter_type[2], [] ( t2* my_storage) -> void {
                tbb::tbb_allocator<t2>().destroy(my_storage);  // my_storage->~t2();
                freeBuffer(my_storage);
                output_counter++; }
        )
    );
    checkCounters(no_pointer_counts);
}
コード例 #14
0
int main (int argc, char ** argv)
{
	struct timeval start,stop;
	if(gettimeofday(&start,NULL) == -1)
	{
		perror("clock gettime\n");
	}
	pthread_mutex_init(&lockGlobal,NULL);
	pthread_mutex_init(&lock,NULL);
	pthread_mutex_lock(&lockGlobal);
	size = (int*) malloc(sizeof size);
	*size = 16;
	global = (struct facteurPremier**)malloc(sizeof(*global));
	*global = (struct facteurPremier*) malloc(sizeof(**global) * (*size));
	int i;
	for(i=0;i<*size;i++)
	{
		(*global)[i].nombre=0;
		(*global)[i].multiplicite=0;
		(*global)[i].file='\0';
	}
	pthread_mutex_unlock(&lockGlobal);

	pthread_mutex_lock(&lock);
	isProducing=0;
	pthread_mutex_unlock(&lock);


	long maxthreads=1;
	int threadNum=0;
	int numofThread=0;
	pthread_t* prodcuteur= (pthread_t*) malloc(sizeof(*prodcuteur)*argc);// talbeau de thread producteur
	pthread_t* consommateur=(pthread_t*) malloc(sizeof(*consommateur)*maxthreads);
	char* argerror;
	char* internet="http://";
	struct buffer* buffer1 = newBuffer(128);
	if(argc>1) {
		isProducing=1;
		for (i = 1; i < argc; i++)
		{
			if(!strcmp(argv[i],"-stdin"))
			{
				struct producteur_param* param=(struct producteur_param*)malloc(sizeof(*param));
				if(param==NULL)
				{
					printf("erreur, pas assez de place\n");
				}
				else
				{
					param->inputName="stdin";
					param->buffer1=buffer1;
					param->fd_read=0;
					param->fd_write=1;
					pthread_create(&prodcuteur[threadNum],NULL,produceFromFD,param);
					numofThread++;
					threadNum++;
				}
			}
			else if(!strcmp(argv[i],"-maxthreads"))
			{
				i++;
				if(i>=argc)
				{
					printf("erreur, pas assez d'argument\n");
				}
				else {
					maxthreads = strtol(argv[i], &argerror, 10); // converti en long
					if (*argerror != '\0') // si erreur dans la conversion
					{
						printf("erreur, argument invalide\n");
						i--;
						maxthreads = 1;
					}
					else
					{
						pthread_t* temp = realloc(consommateur,sizeof(*consommateur)*maxthreads);
						if(temp==NULL)
						{
							printf("erreur de realloc de consommateur\n");
						}
						else
						{
							consommateur=temp;
						}
					}

				}
			}
			else if(strstr(argv[i],internet)!=NULL)
			{
				int fd[2];
				pipe(fd);
				struct producteur_param* param1=(struct producteur_param*)malloc(sizeof(*param1));
				struct producteur_param* param2=(struct producteur_param*)malloc(sizeof(*param2));
				if(param1==NULL)
				{
					printf("erreur pas assez de mémoire\n");
				}
				else
				{
					param1->buffer1=buffer1;
					param1->inputName=argv[i];
					param1->fd_read=fd[0];
					param1->fd_write=fd[1];
					param2->buffer1=buffer1;
					param2->inputName=argv[i];
					param2->fd_read=fd[0];
					param2->fd_write=fd[1];
					pthread_create(&prodcuteur[threadNum],NULL,produceFromInternet,param1);
					numofThread++;
					threadNum++;
					pthread_create(&prodcuteur[threadNum],NULL,produceFromFD,param2);
					threadNum++;
					numofThread++;
				}
			}
			else
			{
				//lecture depuis le fichier
				int fd=open(argv[i],O_RDONLY);
				if(fd==-1)
				{
					printf("erreur de d'ouverture du ficher : %s\n",argv[i]);
				}
				else
				{

					struct producteur_param* param = (struct producteur_param*)malloc(sizeof(*param));
					if(param==NULL)
					{
						printf("erreur pas assez de mémoire\n");
					}
					else
					{
						param->buffer1=buffer1;
						param->inputName=argv[i];
						param->fd_read=fd;
						param->fd_write=1;
						pthread_create(&prodcuteur[threadNum],NULL,produceFromFD,param);
						numofThread++;
						threadNum++;
					}

				}
			}
		}
		int j;
		for(j = 0; j<maxthreads;j++)
		{
			struct consommateur_param* param = (struct consommateur_param*)malloc(sizeof(*param));
			param->lock=&lock;
			param->buffer1=buffer1;
			param->isProducing=&isProducing;
			param->num=j;
			param->global=global;
			param->lockGlobal=&lockGlobal;
			param->size = size;
			pthread_create(&consommateur[j],NULL,consumme,param);
		}

		int cursor;
		for(cursor=0;cursor<numofThread;cursor++)
		{
			pthread_join(prodcuteur[cursor],NULL);
		}
		pthread_mutex_lock(&lock);
		isProducing=0;
		pthread_mutex_unlock(&lock);
		for(cursor=0;cursor<maxthreads;cursor++)
		{
			pthread_join(consommateur[cursor],NULL);
		}

		int succes = searchUniquePrime(*global,size);
		if(gettimeofday(&stop,NULL) == -1)
		{
			perror("clock gettime\n");
		}
		long int sec = stop.tv_sec-start.tv_sec;
		long long int usec = (1000000-start.tv_usec+stop.tv_usec);
		printf("%ld.%lld s\n",sec,usec/1000);
		freeBuffer(buffer1);
		free(consommateur);
		free(size);
		free(*global);
		free(global);
		free(prodcuteur);
		consommateur=NULL;
		size=NULL;
		*global=NULL;
		global=NULL;
		prodcuteur=NULL;
		pthread_mutex_destroy(&lockGlobal);
		pthread_mutex_destroy(&lock);

		return succes;
	}
	return EXIT_FAILURE;
}
コード例 #15
0
ファイル: PolishBam.cpp プロジェクト: Griffan/bamUtil
void FastaFile::allocateBuffer(int bufLength) {
  freeBuffer();
  pcLine = new char[bufLength];
  nMaxLineLength = bufLength;
}
コード例 #16
0
BOOL Matrix::setData (size_t len, size_t dimen, REAL **buf)
{
    freeBuffer();
    return appendData(len, dimen, buf);
}
コード例 #17
0
ファイル: TerrainGrid.cpp プロジェクト: jjiezheng/pap_full
    TerrainGridRenderable::~TerrainGridRenderable() 
    {
		freeBuffer();
    }
コード例 #18
0
ファイル: DataBuffer.c プロジェクト: moritzschaefer/HAs
void deallocateDataBuffer(DataBuffer buffer) {
    if (buffer->count > 0)
        freeBuffer(buffer, buffer->minSeqNo, buffer->minSeqNo + buffer->count - 1);
    free(buffer->data);
    free(buffer);
}
コード例 #19
0
ファイル: Session.c プロジェクト: eson001/eos
void sodero_destroy_session_manager(PSoderoSessionManager object) {
	if (object) {
		sodero_finalize_session_manager(object);
		freeBuffer(object);
	}
}
コード例 #20
0
ファイル: jfConvert.cpp プロジェクト: hkajcy/xcode_tool
CjfConvert::~CjfConvert()
{
    freeBuffer();
}
コード例 #21
0
ファイル: IOMX.cpp プロジェクト: Dmoriarty/frameworks_base
status_t BnOMX::onTransact(
    uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) {
    switch (code) {
        case LIVES_LOCALLY:
        {
            CHECK_INTERFACE(IOMX, data, reply);
            reply->writeInt32(livesLocally((pid_t)data.readInt32()));

            return OK;
        }

        case LIST_NODES:
        {
            CHECK_INTERFACE(IOMX, data, reply);

            List<ComponentInfo> list;
            listNodes(&list);

            reply->writeInt32(list.size());
            for (List<ComponentInfo>::iterator it = list.begin();
                 it != list.end(); ++it) {
                ComponentInfo &cur = *it;

                reply->writeString8(cur.mName);
                reply->writeInt32(cur.mRoles.size());
                for (List<String8>::iterator role_it = cur.mRoles.begin();
                     role_it != cur.mRoles.end(); ++role_it) {
                    reply->writeString8(*role_it);
                }
            }

            return NO_ERROR;
        }

        case ALLOCATE_NODE:
        {
            CHECK_INTERFACE(IOMX, data, reply);

            const char *name = data.readCString();

            sp<IOMXObserver> observer =
                interface_cast<IOMXObserver>(data.readStrongBinder());

            node_id node;

            status_t err = allocateNode(name, observer, &node);
            reply->writeInt32(err);
            if (err == OK) {
                reply->writeIntPtr((intptr_t)node);
            }

            return NO_ERROR;
        }

        case FREE_NODE:
        {
            CHECK_INTERFACE(IOMX, data, reply);

            node_id node = (void*)data.readIntPtr();

            reply->writeInt32(freeNode(node));

            return NO_ERROR;
        }

        case SEND_COMMAND:
        {
            CHECK_INTERFACE(IOMX, data, reply);

            node_id node = (void*)data.readIntPtr();

            OMX_COMMANDTYPE cmd =
                static_cast<OMX_COMMANDTYPE>(data.readInt32());

            OMX_S32 param = data.readInt32();
            reply->writeInt32(sendCommand(node, cmd, param));

            return NO_ERROR;
        }

        case GET_PARAMETER:
        case SET_PARAMETER:
        case GET_CONFIG:
        case SET_CONFIG:
        {
            CHECK_INTERFACE(IOMX, data, reply);

            node_id node = (void*)data.readIntPtr();
            OMX_INDEXTYPE index = static_cast<OMX_INDEXTYPE>(data.readInt32());

            size_t size = data.readInt32();

            void *params = malloc(size);
            data.read(params, size);

            status_t err;
            switch (code) {
                case GET_PARAMETER:
                    err = getParameter(node, index, params, size);
                    break;
                case SET_PARAMETER:
                    err = setParameter(node, index, params, size);
                    break;
                case GET_CONFIG:
                    err = getConfig(node, index, params, size);
                    break;
                case SET_CONFIG:
                    err = setConfig(node, index, params, size);
                    break;
                default:
                    TRESPASS();
            }

            reply->writeInt32(err);

            if ((code == GET_PARAMETER || code == GET_CONFIG) && err == OK) {
                reply->write(params, size);
            }

            free(params);
            params = NULL;

            return NO_ERROR;
        }

        case GET_STATE:
        {
            CHECK_INTERFACE(IOMX, data, reply);

            node_id node = (void*)data.readIntPtr();
            OMX_STATETYPE state = OMX_StateInvalid;

            status_t err = getState(node, &state);
            reply->writeInt32(state);
            reply->writeInt32(err);

            return NO_ERROR;
        }

        case ENABLE_GRAPHIC_BUFFERS:
        {
            CHECK_INTERFACE(IOMX, data, reply);

            node_id node = (void*)data.readIntPtr();
            OMX_U32 port_index = data.readInt32();
            OMX_BOOL enable = (OMX_BOOL)data.readInt32();

            status_t err = enableGraphicBuffers(node, port_index, enable);
            reply->writeInt32(err);

            return NO_ERROR;
        }

        case GET_GRAPHIC_BUFFER_USAGE:
        {
            CHECK_INTERFACE(IOMX, data, reply);

            node_id node = (void*)data.readIntPtr();
            OMX_U32 port_index = data.readInt32();

            OMX_U32 usage = 0;
            status_t err = getGraphicBufferUsage(node, port_index, &usage);
            reply->writeInt32(err);
            reply->writeInt32(usage);

            return NO_ERROR;
        }

        case USE_BUFFER:
        {
            CHECK_INTERFACE(IOMX, data, reply);

            node_id node = (void*)data.readIntPtr();
            OMX_U32 port_index = data.readInt32();
            sp<IMemory> params =
                interface_cast<IMemory>(data.readStrongBinder());

            buffer_id buffer;
            status_t err = useBuffer(node, port_index, params, &buffer);
            reply->writeInt32(err);

            if (err == OK) {
                reply->writeIntPtr((intptr_t)buffer);
            }

            return NO_ERROR;
        }

        case USE_GRAPHIC_BUFFER:
        {
            CHECK_INTERFACE(IOMX, data, reply);

            node_id node = (void*)data.readIntPtr();
            OMX_U32 port_index = data.readInt32();
            sp<GraphicBuffer> graphicBuffer = new GraphicBuffer();
            data.read(*graphicBuffer);

            buffer_id buffer;
            status_t err = useGraphicBuffer(
                    node, port_index, graphicBuffer, &buffer);
            reply->writeInt32(err);

            if (err == OK) {
                reply->writeIntPtr((intptr_t)buffer);
            }

            return NO_ERROR;
        }

        case STORE_META_DATA_IN_BUFFERS:
        {
            CHECK_INTERFACE(IOMX, data, reply);

            node_id node = (void*)data.readIntPtr();
            OMX_U32 port_index = data.readInt32();
            OMX_BOOL enable = (OMX_BOOL)data.readInt32();

            status_t err = storeMetaDataInBuffers(node, port_index, enable);
            reply->writeInt32(err);

            return NO_ERROR;
        }

        case ALLOC_BUFFER:
        {
            CHECK_INTERFACE(IOMX, data, reply);

            node_id node = (void*)data.readIntPtr();
            OMX_U32 port_index = data.readInt32();
            size_t size = data.readInt32();

            buffer_id buffer;
            void *buffer_data;
            status_t err = allocateBuffer(
                    node, port_index, size, &buffer, &buffer_data);
            reply->writeInt32(err);

            if (err == OK) {
                reply->writeIntPtr((intptr_t)buffer);
                reply->writeIntPtr((intptr_t)buffer_data);
            }

            return NO_ERROR;
        }

        case ALLOC_BUFFER_WITH_BACKUP:
        {
            CHECK_INTERFACE(IOMX, data, reply);

            node_id node = (void*)data.readIntPtr();
            OMX_U32 port_index = data.readInt32();
            sp<IMemory> params =
                interface_cast<IMemory>(data.readStrongBinder());

            buffer_id buffer;
            status_t err = allocateBufferWithBackup(
                    node, port_index, params, &buffer);

            reply->writeInt32(err);

            if (err == OK) {
                reply->writeIntPtr((intptr_t)buffer);
            }

            return NO_ERROR;
        }

        case FREE_BUFFER:
        {
            CHECK_INTERFACE(IOMX, data, reply);

            node_id node = (void*)data.readIntPtr();
            OMX_U32 port_index = data.readInt32();
            buffer_id buffer = (void*)data.readIntPtr();
            reply->writeInt32(freeBuffer(node, port_index, buffer));

            return NO_ERROR;
        }

        case FILL_BUFFER:
        {
            CHECK_INTERFACE(IOMX, data, reply);

            node_id node = (void*)data.readIntPtr();
            buffer_id buffer = (void*)data.readIntPtr();
            reply->writeInt32(fillBuffer(node, buffer));

            return NO_ERROR;
        }

        case EMPTY_BUFFER:
        {
            CHECK_INTERFACE(IOMX, data, reply);

            node_id node = (void*)data.readIntPtr();
            buffer_id buffer = (void*)data.readIntPtr();
            OMX_U32 range_offset = data.readInt32();
            OMX_U32 range_length = data.readInt32();
            OMX_U32 flags = data.readInt32();
            OMX_TICKS timestamp = data.readInt64();

            reply->writeInt32(
                    emptyBuffer(
                        node, buffer, range_offset, range_length,
                        flags, timestamp));

            return NO_ERROR;
        }

        case GET_EXTENSION_INDEX:
        {
            CHECK_INTERFACE(IOMX, data, reply);

            node_id node = (void*)data.readIntPtr();
            const char *parameter_name = data.readCString();

            OMX_INDEXTYPE index;
            status_t err = getExtensionIndex(node, parameter_name, &index);

            reply->writeInt32(err);

            if (err == OK) {
                reply->writeInt32(index);
            }

            return OK;
        }

        default:
            return BBinder::onTransact(code, data, reply, flags);
    }
}
コード例 #22
0
ファイル: Image.cpp プロジェクト: gabriel-kent/Halide
 DynImage::Contents::~Contents() {
     if (freeBuffer) {
         fprintf(stderr, "freeBuffer %p\n", &buf);
         freeBuffer(&buf);
     }
 }
コード例 #23
0
void freeBufferPtr (KpGenericPtr_t p)
{
       freeBuffer ((KpGenericPtr_t) p);
}
コード例 #24
0
ファイル: CbrPage.cpp プロジェクト: jsm07b/FBReader
CbrPage::CbrPage(const CbrPage &page) : name(page.name), totalSize(page.totalSize), curSize(page.curSize), buffer(NULL) {
	freeBuffer();
	buffer = new char[page.curSize];
	memcpy(buffer, page.buffer, page.curSize); 
}
コード例 #25
0
void freeSysBufferPtr (KpGenericPtr_t p)
{
       freeBuffer ((KpHandle_t) p);
}
コード例 #26
0
ファイル: CbrPage.cpp プロジェクト: jsm07b/FBReader
CbrPage::~CbrPage() {
	freeBuffer();
}
コード例 #27
0
ファイル: ImageBuffer.cpp プロジェクト: A7med-Shoukry/g3d
ImageBuffer::~ImageBuffer() {
    if (m_buffer) {
        freeBuffer();
    }
}
コード例 #28
0
ファイル: axis.cpp プロジェクト: ICStoolbox/GraphicsEngine
void CglAxis::display(){

    int shaderID = initProgram(pcv->fresnelID());
    GLuint MatrixID = glGetUniformLocation(shaderID, "MVP");
    GLuint colorID  = glGetUniformLocation(shaderID, "COL");
    GLuint MID      = glGetUniformLocation(shaderID, "M");
    GLuint VID      = glGetUniformLocation(shaderID, "V");
    int fill_light_ID           = glGetUniformLocation(shaderID, "FILL");
    int side_light_ID           = glGetUniformLocation(shaderID, "SIDE");
    int back_light_ID           = glGetUniformLocation(shaderID, "BACK");
    int gridID                  = glGetUniformLocation(shaderID, "GRID");


    //GRID
    if( (pcv->profile.displayBottomGrid) && (pScene->scene_type != CGL_GALERY) ){
        enableFog(shaderID);

        glm::mat4 VIEW  = sVIEW();


        glm::mat4 MVP   =   sPROJ()     *
                            sVIEW()     *
                            sMODEL()    *
                            glm::translate(    glm::scale(glm::mat4(1), glm::vec3(pScene->getScale(),1,pScene->getScale())),  glm::vec3(0) );//glm::vec3(sMODEL()[3])   );
        //glm::translate(glm::mat4(1), center) *
        //                    glm::scale(glm::translate( sPROJ() * VIEW * MODEL, center),
        //                               glm::vec3(pScene->getScale(), 1, pScene->getScale())) *
        //                    glm::translate(glm::mat4(1), -center);

        uniform(MatrixID,   MVP);
        uniform(MID,        MODEL);
        uniform(VID,        VIEW);
        uniform(colorID,    glm::vec3(0.,0.,1.0));
        std::vector<pCglLight> lights = pcv->getSubWindow()->getScene()->getLights();
        uniform( fill_light_ID, *(lights[0]->getLightMatrix(pMaterial)));
        uniform( side_light_ID, *(lights[1]->getLightMatrix(pMaterial)));
        uniform( back_light_ID, *(lights[2]->getLightMatrix(pMaterial)));
        uniform(gridID, 1.0f);

        //glLineWidth(1.0);
        //bindBuffer(0, GL_ARRAY_BUFFER, secondaryGridBuffer);
        //glBindAttribLocation( shaderID, 0, "vertex_position");
        //glDrawArrays(GL_LINES, 0, secondaryGrid.size()/3);

        glEnable(GL_BLEND);
        //glLineWidth(2.0);
        bindBuffer(0, GL_ARRAY_BUFFER, mainGridBuffer);
        glBindAttribLocation( shaderID, 0, "vertex_position");
        bindBuffer(1, GL_ARRAY_BUFFER, nBuffer);
        glBindAttribLocation( shaderID, 1, "vertex_normal");
        //glDrawArrays(GL_QUADS, 0, mainGrid.size()/3);


        //STENCIL WRITING

        glEnable(GL_STENCIL_TEST);
        glStencilFunc(GL_ALWAYS, 1, 0xFF); // Set any stencil to 1
        glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
        glStencilMask(0xFF); // Write to stencil buffer
        glDepthMask(GL_FALSE); // Don't write to depth buffer
        glClear(GL_STENCIL_BUFFER_BIT);

        glDrawArrays(GL_QUADS, 0, mainGrid.size()/3);

        glStencilFunc(GL_EQUAL, 1, 0xFF); // Pass test if stencil value is 1
        glStencilMask(0x00); // Don't write anything to stencil buffer
        glDepthMask(GL_TRUE); // Write to depth buffer

        glDisable(GL_STENCIL_TEST);


        //Draw d'un contour

        //glLineWidth(10.0f);
        //uniform(gridID, 0.0f);
        //glEnable(GL_POLYGON_OFFSET_LINE);
        //glPolygonOffset(1.0,1.0);
        //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
        //glDrawArrays(GL_QUADS, 0, mainGrid.size()/3);
        //glDisable(GL_POLYGON_OFFSET_LINE);
        //glLineWidth(1.0f);

        glDisable(GL_BLEND);
        disableFog(shaderID);
        glPolygonMode(GL_FRONT, GL_FILL);
    }


    shaderID = initProgram(pcv->simpleID());
    glPolygonMode(GL_FRONT, GL_LINE);
    MatrixID = glGetUniformLocation(shaderID, "MVP");
    colorID  = glGetUniformLocation(shaderID, "COL");
    MID      = glGetUniformLocation(shaderID, "M");
    VID      = glGetUniformLocation(shaderID, "V");

    //Axes
    if(pcv->profile.displayAxes){
        glDisable(GL_DEPTH_TEST);
        glViewport(0,0,view->width/6,view->width/6);

        glm::mat4 NEUTRAL   = glm::mat4(glm::perspective(70.0, 1.0, view->m_znear, view->m_zfar)) * sVIEW() * glm::mat4(1);
        glm::mat4 M         = glm::scale(NEUTRAL, glm::vec3(view->zoom));
        uniform(MatrixID, M);

        bindBuffer(0, GL_ARRAY_BUFFER, axesBuffer);
        glBindAttribLocation( shaderID, 0, "vertex_position");

        glLineWidth(2.0);
        uniform(colorID, glm::vec3(1,0,0));
        glDrawArrays(GL_LINES, 0, 2);
        uniform(colorID, glm::vec3(0,1,0));
        glDrawArrays(GL_LINES, 2, 4);
        uniform(colorID, glm::vec3(0,0,1));
        glDrawArrays(GL_LINES, 4, 6);

        view->reshape(view->width,view->height);
        glEnable(GL_DEPTH_TEST);
    }

    glLineWidth(1.0);
    glPolygonMode(GL_FRONT, GL_FILL);
    freeBuffer();
}
コード例 #29
0
ファイル: backend_MP.c プロジェクト: dipanjans12/GVirt
void * backend_thread(){
	// connection for listening on a port
	// 2 conn_t cannot be allocated on stack (see comment on conn_t)
	// since cause a seg faults
	conn_t * pConnListen;
	conn_t * pConn;
    pid_t childpid, childpid2;
    int status;

	//int retval = 0;

	// Network state
	// FIXME cuda_bridge_request_t == cuda_packet_t == rpkt_t, this is rediculous
	strm_hdr_t *hdr         = NULL;
	rpkt_t *rpkts           = NULL; // array of cuda packets

	if( (pConnListen = conn_malloc(__FUNCTION__, NULL)) == NULL ) return NULL;
	// this allocates memory for the strm.rpkts, i.e., the array of packets
	if( (pConn = conn_malloc(__FUNCTION__, NULL)) == NULL ) return NULL;


	fprintf(stderr, "**************************************\n");
	fprintf(stderr, "%s.%d: hey, here server thread!\n", __FUNCTION__, __LINE__);
	fprintf(stderr, "**************************************\n");

	// set up the connection
	conn_localbind(pConnListen);
    
    for(;;)
    {
	conn_accept(pConnListen, pConn);   // blocking

    printf("ACCEPTED A CONN***********\n");    
    if((childpid = fork()) == 0)
    {
        
    if((childpid2 = fork()) == 0)
    {    
    // CLOSE the listen connection
    //    conn_close(pConnListen);
        
	// Connection-related structures
	hdr = &pConn->strm.hdr;
	rpkts = pConn->strm.rpkts;   // an array of packets (MAX_REMOTE_BATCH_SIZE)
	// these are buffers for extra data transferred as
	pConn->pReqBuffer = NULL;
	pConn->pRspBuffer = NULL;

    while(1) {

    	p_debug("------------------New RPC--------------------\n");

		memset(hdr, 0, sizeof(strm_hdr_t));
		memset(rpkts, 0, MAX_REMOTE_BATCH_SIZE * sizeof(rpkt_t));
		pConn->request_data_size = 0;
		pConn->response_data_size = 0;

		pConn->pReqBuffer = freeBuffer(pConn->pReqBuffer);
		pConn->pRspBuffer = freeBuffer(pConn->pRspBuffer);

		//recv the header describing the batch of remote requests
		if (1 != get(pConn, hdr, sizeof(strm_hdr_t))) {
			break;
		}
		p_debug(" received request header. Expecting  %d packets. And extra request buffer of data size %d\n",
				hdr->num_cuda_pkts, hdr->data_size);

		if (hdr->num_cuda_pkts <= 0) {
			p_warn("Received header specifying zero packets, ignoring\n");
			continue;
		}

        // Receive the entire batch.
		// first the packets, then the extra data (reqbuf)
		//
		// let's assume that we have enough space. otherwise we have a problem
		// pConn allocates the buffers for incoming cuda packets
		// so we should be fine
		if(1 != get(pConn, rpkts, hdr->num_cuda_pkts * sizeof(rpkt_t))) {
			break;
		}
		p_info("Received %d packets, each of size of (%lu) bytes\n",
				hdr->num_cuda_pkts, sizeof(rpkt_t));

		p_info( "Received method %s (method_id %d) from Thr_id: %lu.\n",
		 methodIdToString(rpkts[0].method_id), rpkts[0].method_id, rpkts[0].thr_id);

		// receiving the request buffer if any
		if(hdr->data_size > 0){
			p_info("Expecting data size/Buffer: %u, %d.\n",
					hdr->data_size, pConn->request_data_size);
			// let's assume that the expected amount of data will fit into
			// the buffer we have (size of pConn->request_data_buffer

			// allocate the right amount of memory for the request buffer
			pConn->pReqBuffer = malloc(hdr->data_size);
			if( mallocCheck(pConn->pReqBuffer, __FUNCTION__, NULL) == ERROR ){
				break;
			}

			//assert(hdr->data_size <= TOTAL_XFER_MAX);
			if(1 != get(pConn, pConn->pReqBuffer, hdr->data_size)){
				pConn->pReqBuffer = freeBuffer(pConn->pReqBuffer);
				break;
			}
			pConn->request_data_size = hdr->data_size;
			p_info( "Received request buffer (%d bytes)\n", pConn->request_data_size);
		}

		// execute the request
		pkt_execute(&rpkts[0], pConn);

		// we need to send the one response packet + response_buffer if any

		// @todo you need to check if he method needs to send
		// and extended response - you need to provide the right
		// data_size

		if( strm_expects_response(&pConn->strm) ){

			// send the header about response
			p_debug( "pConn->response_data_size %d\n", pConn->response_data_size);
			if (conn_sendCudaPktHdr(&*pConn, 1, pConn->response_data_size) == ERROR) {
				p_info( "__ERROR__ after : Sending the CUDA packet response header: Quitting ... \n");
				break;
			}

			// send the standard response (with cuda_error_t, and simple arguments etc)
			if (1 != put(pConn, rpkts, sizeof(rpkt_t))) {
				p_info("__ERROR__ after : Sending CUDA response packet: Quitting ... \n");
				break;
			}
			p_info("Response packet sent.\n");

			// send the extra data if you have anything to send
			if( pConn->response_data_size > 0 ){
				if (1 != put(pConn, pConn->pRspBuffer, pConn->response_data_size)) {
					p_info("__ERROR__ after: Sending accompanying response buffer: Quitting ... \n"
							);
					break;
				}
				p_info( "Response buffer sent (%d) bytes.\n", pConn->response_data_size);
			}
		}
    }

    freeBuffer(pConn->pReqBuffer);
    freeBuffer(pConn->pRspBuffer);
	conn_close(pConnListen);
	conn_close(pConn);

	free(pConnListen);
	free(pConn);

	return NULL;
    } //if(childpid2==0)   
    else
        exit(0);
        
        
    
    } //if(childpid==0)

        //CLOSE THE other conn
        conn_close(pConn);
        waitpid(childpid, &status, NULL);
    }//for(;;)
}
コード例 #30
0
Matrix::~Matrix ()
{
    freeBuffer();
}