int main(int argc, char *argv[]){
	/* 1. Get command line arguments */
	if (argc != 4){
		printf("needs four arguments");
		return -1;
	}
	int timeLimit = atoi(argv[1]);
	int numProducers = atoi(argv[2]);
	int numConsumers = atoi(argv[3]);
	/* 2. Initialize buffer */
	initializeBuffer();
	/* 3. Create producer thread(s) */
	pthread_t prod_tid[numProducers];
	pthread_t con_tid[numConsumers];
	int i =0;
	for(i = 0; i < numProducers; i++){
		pthread_create(&prod_tid[i], NULL, producer, NULL);
	}
	/* 4. Create consumer thread(s) */
	for(i = 0; i < numConsumers; i++){
		pthread_create(&con_tid[i], NULL, consumer, NULL);
	}
	/* 5. Sleep */
	sleep(timeLimit);
	/* 6. Exit */
	return 0;
}
Пример #2
0
PowerSupply::PowerSupply()
{
    _connected = false;
    _frame = NULL;
    _proto = &oldProtocol;
    initializeBuffer();
}
int kmain() {
	initializeBuffer();
	cursor = 0;

	/* Borra la pantalla. */ 
	clearScreen();

	/* CARGA DE IDT */
	setup_IDT_content();

	/* Carga de IDTR */
	setup_IDTR();

	_Cli();

	_mascaraPIC1(0xFC); /*Habilito timer tick, teclado*/
    _mascaraPIC2(0xFF); /*Las interrupciones del segundo PIC quedan deshabilitadas*/

	_Sti();

	showSplashScreen();

	shell();

	_Cli();
	goodbye();
	_Sti();
	
	return 0;
}
Пример #4
0
void PowerSupply::switchToNewProtocol()
{
    if (_proto != &newProtocol)
    {
        _proto = &newProtocol;
        initializeBuffer();
    }
}
Пример #5
0
PowerSupply::PowerSupply(const string strHost, const string strPort)
{    
    _connected = false;
    _frame = NULL;
    _proto = &oldProtocol;
    initializeBuffer();
    connect(strHost, strPort);
}
Пример #6
0
BufferLog::BufferLog(void* address, const size_t totalSize)
    : _buffer(address)
    , _totalSize(totalSize)
    , _inCallbackStack(false)
{
    initializeBuffer();
    Header* h = header(_buffer);
    h->mutex.clear();
}
 void Plotter2DDisplay::subscribe()
 {
   initializeBuffer();
   std::string topic_name = update_topic_property_->getTopicStd();
   if (topic_name.length() > 0 && topic_name != "/") {
     ros::NodeHandle n;
     sub_ = n.subscribe(topic_name, 1, &Plotter2DDisplay::processMessage, this);
   }
 }
Пример #8
0
BufferLog::BufferLog(void* address, const size_t totalSize,
                     MemoryExhaustedCallback callback)
    : _buffer(address)
    , _totalSize(totalSize)
    , _callback(std::move(callback))
    , _inCallbackStack(false)
{
    initializeBuffer();
    Header* h = header(_buffer);
    h->mutex.clear();
}
Пример #9
0
void DTIDEDebuggingWindow::setMemoryData(QByteArray* bytes)
{
    initializeBuffer();
    QSharedPointer<QBuffer> buff_ptr(buffer);

    data = bytes;

    buffer->close();
    buffer->setBuffer(data);
    buffer->open(QIODevice::ReadWrite);

    memoryView->setData(buff_ptr);
}
Пример #10
0
void BufferLog::setBuffer(void* buffer, size_t totalSize) {
    Header* h = header(_buffer);
    // if test_and_set returns 'true', someone else is in the critical section
    // unless we are currently in a callstack containing the callback function. In which
    // case we are already safe
    while (h->mutex.test_and_set() && !_inCallbackStack) {}
    // the moment we return, we own the mutex

    _buffer = buffer;
    _totalSize = totalSize;
    initializeBuffer();
    
    if (!_inCallbackStack)
        // only release the mutex if we are not in the callback stack
        h->mutex.clear();
}
Пример #11
0
DTIDEDebuggingWindow::DTIDEDebuggingWindow(QWidget* parent): QDialog(parent)
{
    buffer = 0;

    setupUi(this);
    connect(btn_step_into, SIGNAL(clicked()), this, SIGNAL(step()));
    connect(btn_resume, SIGNAL(clicked()), this, SIGNAL(resume()));
    connect(btn_pause, SIGNAL(clicked()), this, SIGNAL(pause()));

    initializeBuffer();

    memoryView->setWordWidth(2);
    memoryView->setShowAsciiDump(false);
    memoryView->setRowWidth(8);
    memoryView->setShowAddressSeparator(false);
}
Пример #12
0
			inAudioCapture(WAVEFORMATEX *pwfx=NULL,int samplingRate=44100) : 
				timeElapsed(1),samplingRate(samplingRate),byteReady(false)
			{
				if(!pwfx)
				{
					waveFormatInit();
				}
				else
				{
					this->pwfx = *pwfx; 
				}
				data_size = this->samplingRate*timeElapsed;
				dataIn = new int[data_size];

				initializeBuffer();
				#if WRITEWAVE
				handle = mmioOpen("test.wav", 0, MMIO_CREATE | MMIO_WRITE);
				#endif
			}
Пример #13
0
int main( int argc, char ** argv )
{
   #define BUF_SIZE 16
   #define TOTAL_COPY_CHECKS 1024
   char mem[ BUF_SIZE ] ;
   char buf[ BUF_SIZE * BUF_MULTIPLICITY ] ; 
   char copy[ BUF_SIZE ] ; 
   int numCopies = 0 ;
   int iterations = 0 ;
   int verbose = VERBOSE ;
   initializeBuffer( mem, sizeof(mem) ) ;

   for ( ; numCopies < TOTAL_COPY_CHECKS ; iterations++ )
   {
RETRY:
      char * src = randomizeString( buf, mem, BUF_SIZE ) ;
      size_t len = strlen( src ) ;
      assert( len < BUF_SIZE ) ;

      strcpy( copy, src ) ;

      char * dest ;
      ssize_t diff ;

      for ( int n = 0 ; ; )
      {
#if defined OVERLAPPED
         dest = &buf[ rand() % ( sizeof(buf) - 1 ) ] ;
#else
         dest = &buf[ BUF_SIZE + rand() % ( BUF_SIZE - 1 ) ] ;
#endif
         diff = dest - src ;

//#define REQUIRE_DEST_LESSER_THAN_SRC
#if defined REQUIRE_DEST_LESSER_THAN_SRC
         if ( diff > 0 )
         {
            continue ;
         }
#endif
         if ( diff < 0 )
         {
            diff = -diff ;
         }

         if ( pred( diff, len ) && (&dest[len + 1] < &buf[BUF_SIZE * BUF_MULTIPLICITY -1]) )
         {
            break ;
         }

         if ( ++n > 3 )
         {
            goto RETRY ;
         }
      }

      if ( verbose )
      {
         printf( "buf:\t[%p, %p]\n"
                 "dest:\t[%p, %p]\n"
                 "src:\t[%p, %p]\n"
                 "strlen + 1:\t%u\n"
                 "diff:\t%d\n",
                 buf,
                 buf + sizeof(buf) - 1,
                 dest,
                 dest + len + 1,
                 src,
                 src + len + 1,
                 (unsigned)len + 1,
                 (int)diff ) ;
      }
      else
      {
         printf( "." ) ;

         if ( (0 == (numCopies % 80)) && numCopies )
         {
            printf( "\n" ) ;
         }
      }

      numCopies++ ;

      systemStrcpy( dest, src ) ;
      if ( 0 != strcmp( dest, copy ) )
      {
         printf( "pattern: '%s'\n"
                 "dest: '%s'\n"
                 "src: %p\n"
                 "dest: %p\n"
                 "diff: %d\n"
                 "strlen + 1: %u\n",
                 copy,
                 dest,
                 src,
                 dest,
                 (int)diff,
                 (unsigned)len + 1 ) ;

         break ;
      }
   }

   printf( "\nDONE\n" ) ; 

   return iterations ;
}
int main(int argc, char * argv[])
{
    int numPointsPerDimension;
    int verbose = 0;
    double omega;
    double epsilon;
    double * * points;
    struct timeval startTime;
    struct timeval endTime;
    double duration;
    double breakdown = 0;
    int numIterations;
    double maxDiff, tmpMaxDiff;

    int numProcesses;
    int workingProcesses;
    int myRank;
    MPI_Status status;
    MPI_Request requestUpSend, requestUpRecv;
    MPI_Request requestDownSend, requestDownRecv;
    int partitions;
    int remainder;
    int width;
    int i, k;
    int buffSize;
    int startRow;

    double * upPointsSend, * upPointsRecv;
    double * downPointsSend, * downPointsRecv;

    int upperProc, lowerProc;
    struct timeval startInterval;
    struct timeval endInterval;

    if (argc < 2)
    {
        fprintf(stderr, "ERROR: Too few arguments!\n");
        printUsage(argv[0]);
        exit(1);
    }
    else if (argc > 3)
    {
        fprintf(stderr, "ERROR: Too many arguments!\n");
        printUsage(argv[0]);
        exit(1);
    }
    else
    {
        int argIdx = 1;
        if (argc == 3)
        {
            if (strncmp(argv[argIdx], OPTION_VERBOSE, strlen(OPTION_VERBOSE)) != 0)
            {
                fprintf(stderr, "ERROR: Unexpected option '%s'!\n", argv[argIdx]);
                printUsage(argv[0]);
                exit(1);
            }
            verbose = 1;
            ++argIdx;
        }
        numPointsPerDimension = atoi(argv[argIdx]);
        if (numPointsPerDimension < 2)
        {
            fprintf(stderr, "ERROR: The number of points, '%s', should be "
                "a numeric value greater than or equal to 2!\n", argv[argIdx]);
            printUsage(argv[0]);
            exit(1);
        }
    }
    
    MPI_Init(&argc, &argv);

    /* get info about how may processes are running 
     * and what is your rank number */
    MPI_Comm_size(MPI_COMM_WORLD, &numProcesses);
    MPI_Comm_rank(MPI_COMM_WORLD, &myRank);

    /* calculate nominal size of data per each process */
    partitions = numPointsPerDimension / numProcesses;

    /* calculate number of processes with the additional row of data */
    remainder = numPointsPerDimension % numProcesses;

    /* according to myRank, set the width of the table */
    width = (myRank < remainder) ? partitions + 1 : partitions;
    
    /* decide how many processes are required to do the calculation */
    workingProcesses = (numProcesses > numPointsPerDimension) ? numPointsPerDimension : numProcesses;

    /* terminate processes that won't be used */
    /* start of copied part of code */
    MPI_Comm MY_WORLD = MPI_COMM_WORLD;
    if(workingProcesses < numProcesses)
    {
        MPI_Group world_group;
        MPI_Comm_group(MPI_COMM_WORLD, &world_group);
        
        // Remove all unnecessary ranks
        MPI_Group new_group;
        int ranges[1][3] = {{workingProcesses, (numProcesses - 1), 1}};
        MPI_Group_range_excl(world_group, 1, ranges, &new_group);

        // Create a new communicator
        MPI_Comm_create(MPI_COMM_WORLD, new_group, &MY_WORLD);

        if (MY_WORLD == MPI_COMM_NULL)
        {
            // Bye bye cruel world
            MPI_Finalize();
            exit(0);
        }
    }
    /* end of copied part of code */
    /* source: http://stackoverflow.com/questions/13774968/mpi-kill-unwanted-processes */


    /* set the calculation parameters */
    omega = getOmega(numPointsPerDimension);
    epsilon = getEpsilon(numPointsPerDimension);
    
    /* allocate points table for each process */
    points = allocatePoints(numPointsPerDimension, width, numProcesses);
    if (points == NULL)
    {
        freePoints(points, width, myRank);
        fprintf(stderr, "ERROR: Malloc failed!\n");
        exit(1);
    }
    
    /* size of the table to send per each iteration */
    buffSize = numPointsPerDimension / 2 + numPointsPerDimension % 2 ;
    
    /* initialize additional buffers for communication */
    upPointsSend = initializeBuffer(buffSize);
    upPointsRecv = initializeBuffer(buffSize);
    downPointsSend = initializeBuffer(buffSize);
    downPointsRecv = initializeBuffer(buffSize);
    
    /* process #0 sends to others separate parts of the table
     * others wait for incoming data */
    if (myRank == 0)
    { 
        startRow = numPointsPerDimension;
        for(k = workingProcesses - 1; k >= 0 ; --k)
        {
            width = (k < remainder) ? partitions + 1 : partitions;
            
            /* initialize points */
            initializePoints(points, startRow - width, width, numPointsPerDimension);
        
            /* send table to k-th process */
            if(k != 0)
            {
                for(i = 0; i < width; ++i)
                {
                    MPI_Send(points[i], numPointsPerDimension, MPI_DOUBLE, k, 123, MY_WORLD);
                }
            }
            startRow -= width;
        }        
    } 
    else 
    {
        if(myRank < workingProcesses)
        {
            for(i = 0; i < width; ++i)
            {
                MPI_Recv(points[i], numPointsPerDimension, MPI_DOUBLE, 0, 123, MY_WORLD, &status);
            }
        }
    }

    /* remember with which processes you comunicate */ 
    upperProc = myRank == 0 ? MPI_PROC_NULL : myRank - 1;
    lowerProc = myRank == workingProcesses - 1 ? MPI_PROC_NULL : myRank + 1;
    
    /* here each process has it's own data set for computations */

    if(remainder > 0)
    {
        startRow = (myRank < remainder) ? myRank * (partitions + 1) : myRank * partitions + remainder;
    }
    else 
    {
        startRow = myRank * partitions;
    }

    if(gettimeofday(&startTime, NULL))
    {
        freePoints(points, width, myRank);
        fprintf(stderr, "ERROR: Gettimeofday failed!\n");
        exit(1);
    }
    
    /* Start of computations. */
    
    numIterations = 0;
    do
    {
        int i, j, color;
        maxDiff = 0.0;
        for (color = 0; color < 2; ++color)
        {

            /* fill downPointsSend with the last row of points data */
            setDataBuffer(downPointsSend, points, width - 1, 1 + ((startRow + width) % 2 == color ? 1 : 0), numPointsPerDimension);

            if(gettimeofday(&startInterval, NULL))
		    {
		        freePoints(points, width, myRank);
		        fprintf(stderr, "ERROR: Gettimeofday failed!\n");
		        exit(1);
	        }
            
            MPI_Isend(downPointsSend, buffSize, MPI_DOUBLE, lowerProc, color, MY_WORLD, &requestDownSend);
            MPI_Irecv(downPointsRecv, buffSize, MPI_DOUBLE, lowerProc, color, MY_WORLD, &requestDownRecv);
            
            if(gettimeofday(&endInterval, NULL))
		    {
		        freePoints(points, width, myRank);
		        fprintf(stderr, "ERROR: Gettimeofday failed!\n");
		        exit(1);
		    }
	
		    breakdown += ((double)endInterval.tv_sec + ((double)endInterval.tv_usec / 1000000.0)) - 
	                     ((double)startInterval.tv_sec + ((double)startInterval.tv_usec / 1000000.0));

            /* fill upPointsSend with the last row of points data */
            setDataBuffer(upPointsSend, points, 0, 1 + ((startRow - 1) % 2 == color ? 1 : 0), numPointsPerDimension);

		    if(gettimeofday(&startInterval, NULL))
		    {
		        freePoints(points, width, myRank);
		        fprintf(stderr, "ERROR: Gettimeofday failed!\n");
		        exit(1);
		    }

		    MPI_Isend(upPointsSend, buffSize, MPI_DOUBLE, upperProc, color, MY_WORLD, &requestUpSend);
            MPI_Irecv(upPointsRecv, buffSize, MPI_DOUBLE, upperProc, color, MY_WORLD, &requestUpRecv);
			
		    if(gettimeofday(&endInterval, NULL))
		    {
		        freePoints(points, width, myRank);
		        fprintf(stderr, "ERROR: Gettimeofday failed!\n");
		        exit(1);
		    }
		
		    breakdown += ((double)endInterval.tv_sec + ((double)endInterval.tv_usec / 1000000.0)) - 
        	             ((double)startInterval.tv_sec + ((double)startInterval.tv_usec / 1000000.0));

            /* computations of the first row requires data that has to be recieved from other process */
            MPI_Wait(&requestUpRecv, &status);

            for (i = 0; i < width; ++i)
            {
 
                /* before computing the last row of its data, 
                 * process has to be sure that it has required
                 * row from process rank+1 */
		        if(i == width - 1)
                {
                	MPI_Wait(&requestDownRecv, &status);
                }

                for (j = 1 + ((startRow+i) % 2 == color ? 1 : 0); j < numPointsPerDimension - 1; j += 2)
                {
                    if( (myRank != 0 || i != 0 ) && (myRank != workingProcesses - 1 || i != width - 1) )
                    {
                        
                        double tmp, diff;
                        double down, up;
                        int jIdx = (j - 1 - ((startRow + i) % 2 == color ? 1 : 0))/ 2;
                        
                        /* decide if up or down value should be taken from additional buffers */
                        up = (i == 0) ? upPointsRecv[jIdx] : points[i-1][j];
                        down = (i == width - 1) ? downPointsRecv[jIdx] : points[i+1][j];
                        
                        /* calculate final value */
                        tmp = (up + down + points[i][j - 1] + points[i][j + 1]) / 4.0;
                        diff = points[i][j];
                        points[i][j] = (1.0 - omega) * points[i][j] + omega * tmp;
                        
                        diff = fabs(diff - points[i][j]);
                        if (diff > maxDiff)
                        {
                            maxDiff = diff;
                        }
                    }
                }
            }
            MPI_Barrier(MY_WORLD);
        }
    	
        if(gettimeofday(&startInterval, NULL))
        {
            freePoints(points, width, myRank);
            fprintf(stderr, "ERROR: Gettimeofday failed!\n");
            exit(1);
        }
        
        /* find new maxDiff among all processes */
        MPI_Allreduce(&maxDiff, &tmpMaxDiff, 1, MPI_DOUBLE, MPI_MAX, MY_WORLD );
        maxDiff = tmpMaxDiff;

        if(gettimeofday(&endInterval, NULL))
        {
            freePoints(points, width, myRank);
            fprintf(stderr, "ERROR: Gettimeofday failed!\n");
                exit(1);
        }
        
        breakdown += ((double)endInterval.tv_sec + ((double)endInterval.tv_usec / 1000000.0)) - 
                     ((double)startInterval.tv_sec + ((double)startInterval.tv_usec / 1000000.0));

        ++numIterations;
    }
    while (maxDiff > epsilon);

    /* End of computations. */
 
    if(gettimeofday(&endTime, NULL))
    {
        freePoints(points, width, myRank);
        fprintf(stderr, "ERROR: Gettimeofday failed!\n");
        exit(1);
    }

    /* calculate how long did the computation lasted */
    duration =
        ((double)endTime.tv_sec + ((double)endTime.tv_usec / 1000000.0)) - 
        ((double)startTime.tv_sec + ((double)startTime.tv_usec / 1000000.0));

    /* we choose the process whose execution lasted for the longest time */     
    double maxDuration;
    MPI_Allreduce(&duration, &maxDuration, 1, MPI_DOUBLE, MPI_MAX, MY_WORLD);
   
    if(myRank==0)
    {
        fprintf(stderr,
            "Statistics: duration(s)=%.10f breakdown=%.10f #iters=%d diff=%.10f epsilon=%.10f\n",
            maxDuration, breakdown, numIterations, maxDiff, epsilon);
    }
  
    if (verbose) {
        
        MPI_Barrier(MY_WORLD);
    
        /* process #0 is responsible for printing results of computation 
         * others send their data straight to it */
        if(myRank != 0 && myRank < workingProcesses) 
        {
            for(k = 0; k < width ; ++k)
            {
                MPI_Send(points[k], numPointsPerDimension, MPI_DOUBLE, 0, 123, MY_WORLD);
            }
        }
        else if(myRank == 0)
        {
            printPoints(points, width, numPointsPerDimension);
            for(i = 1; i < workingProcesses; ++i)
            {
                width = (i < remainder) ? partitions + 1 : partitions;
                
                for (k = 0 ; k < width ; ++k)
                {
                    MPI_Recv(points[k], numPointsPerDimension, MPI_DOUBLE, i, 123, MY_WORLD, &status);
                }

                printPoints(points, width, numPointsPerDimension);
            }
        }
    }
    
    /* free all the memory that was allocated */
    freePoints(points, width, myRank);
    free(downPointsSend);
    free(upPointsSend);
    free(downPointsRecv);
    free(upPointsRecv);
     
    MPI_Finalize();
    
    return 0;
}
// 线程函数, 想服务器发送数据
DWORD WINAPI SendThread( LPVOID lpParam ) {
	SendData* sd = ( struct SendData* )lpParam;
	WSADATA wsd;

	SOCKET sockfd;
	SOCKADDR_IN addr;
	HOSTENT* host = NULL;
	int theport = 80;

	if ( WSAStartup( MAKEWORD( 2, 2 ), &wsd ) != 0 ) {

		cout << "\n\t wsa startup faild, error code: " << WSAGetLastError() << endl;
		// exit( 0 );
		return 0;
	}

	host = gethostbyname( sd->host );
	if ( host == NULL ) {
		cout << "host name is error, errorcode: " << WSAGetLastError() << endl;
		WSACleanup();
		// exit( 0 );
		return 0;
	}
	cout << "host: " << host->h_name;
	
	// port
	theport = sd->port;

	addr = initializeSockaddr( host, theport );
	sockfd = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
	if ( INVALID_SOCKET == sockfd ) {
		cout << "sockfd error, error code: " << WSAGetLastError() << endl;
		WSACleanup();
		// exit( 0 );
		return 0;
	}
	cout << "connect...." << endl;
	if ( 0 > connect( sockfd, ( struct sockaddr* )&addr, sizeof( addr ) ) ) {
		cout << "\n\t error connect, error code: " << WSAGetLastError() << endl;
		WSACleanup();
		// exit( 0 );
		return 0;
	}
	//char* sendbuffer;// = initializeBuffer( 1024 );
	//// 准备要发送的数据
	//sendbuffer = prepardatatosend( );
	//if ( send( sockfd, sendbuffer, strlen( sendbuffer ) + 1, 0 ) == SOCKET_ERROR ) {
	//	cout << " \n\t error code: " << WSAGetLastError() << endl;
	//	// exit( 0 );
	//	return 0;
	//}
	char* recvbuffer = initializeBuffer( 128 );

	// 保存接受的数据
	ofstream output;
	output.open( "001.txt", ios::app );
	if ( output.is_open() ) {
		cout << "open success" << endl;
	}

	while ( recv( sockfd, recvbuffer, strlen( recvbuffer ), 0 ) > 0 ) {
		int lengthrecv = strlen( recvbuffer );
		cout << "recv:" << lengthrecv << endl;
		for ( int j = 0; j < lengthrecv; j++ ) {
			cout << recvbuffer[ j ];
			output << recvbuffer[ j ];
		}
		//delete recvbuffer;
		recvbuffer = initializeBuffer( 128 );
		cout << endl;
	}
	output.close();
	closesocket( sockfd );
	WSACleanup();

	return 0;
	
}
 void Plotter2DDisplay::updateBufferSize()
 {
   buffer_length_ = buffer_length_property_->getInt();
   initializeBuffer();
 }