Beispiel #1
0
// thread to change newlines to spaces
void *newlineToSpace(void *t){
  ThreadInit *init = t;
  char theCharacter;
  char space = ' '; // used for produce() in the case it needs a space
  int toBreak = 0; // toBreak is boolean initialized to FALSE

  while(toBreak == 0) {
    //if "from" is done inserting, and there are no elements, break
    down(init->from_bin_sem);
    if( *(init->from->doneInserting) == 1){
      if( (*init->from->numElements == 0)){
        toBreak = 1;
      }
    }

    if (toBreak == 0){ // do only if toBreak is FALSE
      theCharacter = consume(init->from);
      down(init->to_bin_sem);
      if (theCharacter == '\n'){
        produce(init->to, &space);
      }
      else{
        produce(init->to, &theCharacter);
      }
      up(init->to_bin_sem);
    }
    up(init->from_bin_sem);
  }

  // lets next buffer know when to stop consuming
  down(init->to_bin_sem);
  *(init->to->doneInserting) = 1;
  up(init->to_bin_sem);

  //done, exit thread
  st_thread_exit(NULL);
}
Beispiel #2
0
int main() {
  double value[1];
  int c = 3;
#pragma smecy stream_loop
  while (1) {
#pragma smecy stage arg(1,out) map(PE,1)
      produce(value);
#pragma smecy stage arg(1,inout) map(CPU, 5)
      scale(value, c);
#pragma smecy stage label(122) arg(1,in) map(GPU, 46)
      display(value);
	}

  return 0;
}
Beispiel #3
0
 void consume() {
     // Consume an input buffer.
     {
         unique_lock<mutex> lock(_in.getMutex());
         while (_in.empty() == true) {
             _in.waitForNonEmpty(lock);
             if (_stopManager == true) {
                 return;
             }
         }
         _inputBuf = &_in.getForRead();
         produce();
         _in.advanceReadPos();
     }
     _in.signalNonFull();
 }
Beispiel #4
0
int main(int argc, char const *argv[])
{
	int i;
	freopen("data.out","w",stdout);  // Redirect output to a file
	empty_sem = sem_open(EMPTY_SEM_NAME, O_CREAT, S_IRWXU|S_IRWXG|S_IRWXO, EMPTY_SEM_VALUE); // mode = 00700|00070|00007
	full_sem = sem_open(FULL_SEM_NAME, O_CREAT, S_IRWXU|S_IRWXG|S_IRWXO, FULL_SEM_VALUE); // mode = 00700|00070|00007
	mutex_sem = sem_open(MUTEX_SEM_NAME, O_CREAT, S_IRWXU|S_IRWXG|S_IRWXO, MUTEX_SEM_VALUE); // mode = 00700|00070|00007
	fd = open("buffer", O_CREAT|O_TRUNC|O_RDWR, 0666);
	if (fd<0){
		printf("Failed to open buffer file!\n");
		return -1;
	}
	lseek(fd, 0, SEEK_SET);	// Set RW position to start of file
	write(fd, (char*)(&out), sizeof(int));	// Write read position to the buffer file
	// Create a producer process
	pid_t pro_pid = fork();
	if (pro_pid==0){
		produce();
		return 0;	// Finish the producer process
	}else if(pro_pid<0){
		// Error encountered when create a producer process
		printf("Error encountered while creating a producer process!\n");
		return -1;
	}else{
		// This is in the parent process
		// printf("Producer process PID: %d\n", pro_pid);
	}
	pid_t con_pids[N];
	for (i=0; i<N; i++){
		// Create a consumer process
		con_pids[i] = fork();
		if (con_pids[i] == 0){
			// In the consumer process
			consume();
			return 0;	// Finish the consumer process
		}else if (con_pids[i] < 0){
			printf("Error encountered while creating the consumer process\n");
			return -1;
		}
	}
	// for (i=0; i<N; i++) printf("Consumer process #%d PID: %d\n", i, con_pids[i]);
	sem_unlink(EMPTY_SEM_NAME);
	sem_unlink(FULL_SEM_NAME);
	sem_unlink(MUTEX_SEM_NAME);
	for (i=0; i<N+1; i++) wait(NULL);
	return 0;
}
Beispiel #5
0
int main(int argc, char *argv[])
{
  int listenfd, connfd, port, clientlen;
  struct sockaddr_in clientaddr;
  int i;

  // thread pool
  pthread_t *threads = (pthread_t*) malloc(sizeof(pthread_t) * t_num); 
  getargs(&port, &t_num, &b_sz, argc, argv);

  q.head = 0;
  q.tail = -1;
  q.sz = 0;
  q.req_buf = (int*) malloc(sizeof(int) * b_sz);
  memset(q.req_buf, -1, sizeof(int) * b_sz);
  /*for (i = 0; i < b_sz; ++i)
    printf("%d, ", q.req_buf[i]);*/

  pthread_mutex_init(&m, NULL);
  pthread_cond_init(&not_full, NULL);
  pthread_cond_init(&empty, NULL);

  for (i = 0; i < t_num; ++i) {
    if (pthread_create(&threads[i], NULL, consume, NULL) != 0) {
      perror("Thread create failure.\n");
      exit(1);
    }
    //printf("Thread %d created.\n", i+1);
  }

  listenfd = Open_listenfd(port);
  while (1) {
    clientlen = sizeof(clientaddr);
    connfd = Accept(listenfd, (SA *)&clientaddr, (socklen_t *) &clientlen);
    produce(connfd);
    // 
    // CS537: In general, don't handle the request in the main thread.
    // Save the relevant info in a buffer and have one of the worker threads 
    // do the work. However, for SFF, you may have to do a little work
    // here (e.g., a stat() on the filename) ...
    // 
    //requestHandle(connfd);

    //Close(connfd);
  }

}
Beispiel #6
0
Try<Nothing> JsonSource::RunTests(const std::string& jsonSource) {
  Try<mesos::FixtureResourceUsage> usages = JsonSource::ReadJson(jsonSource);
  if (usages.isError()) {
    LOG(ERROR) << "JsonSource failed: " << usages.error() << std::endl;
  }

  for (auto itr = usages.get().resource_usage().begin();
      itr != usages.get().resource_usage().end();
      itr++) {
    Try<Nothing> ret = produce(*itr);

    // Stop the pipeline in case of error.
    if (ret.isError()) return ret;
  }

  return Nothing();
}
Beispiel #7
0
void* thread_producer(void *arg)
{
/*	puts("thread_producer created"); */
	while (control) {
		puts("thread_producer running");
		printf("pthread_id = %ld\n", pthread_self());
		sem_wait(&empty);
		pthread_mutex_lock(&mutex);
		produce();
		append();
		print_status();
		sleep(1);
		pthread_mutex_unlock(&mutex);
		sem_post(&full);
	}
	return EXIT_SUCCESS;
}
Beispiel #8
0
int main() //@ : main_full(prodcons)
    //@ requires module(prodcons, true);
    //@ ensures true;
{
    //@ open_module();
    //@ close exists(integer0);
    init();
    for (;;)
      //@ invariant producer(integer0) &*& consumer(integer0);
    {
      int *x = malloc(1 * sizeof(int));
      if (x == 0) abort();
      //@ close integer0(x);
      produce(x);
      int *y = consumer();
      //@ open integer0(y);
      free(y);
    }
}
Beispiel #9
0
void firm::activate(string market_type)
{
    if (market_type == "labor_market")
    {
        set_vacancies();
    }
    else
    {
        if (type == "foreign")
        {
            storage = std::numeric_limits<float>::max();
        }
        else
        {
            produce();
            storage += production;
            price = pricing();
        }
    }
}
Beispiel #10
0
 void ArrayProducer::ComputeState::produceJSON( size_t index, size_t count, JSON::Encoder &jg ) const
 {
   RC::ConstHandle<RT::Desc> elementDesc = m_arrayProducer->getElementDesc();
   size_t allocSize = elementDesc->getAllocSize();
   size_t totalAllocSize = allocSize * count;
   void *datas = alloca( totalAllocSize );
   memset( datas, 0, totalAllocSize );
   produce( index, count, datas );
   {
     JSON::ArrayEncoder jag = jg.makeArray();
     uint8_t *data = reinterpret_cast<uint8_t *>( datas );
     for ( size_t i=0; i<count; ++i )
     {
       JSON::Encoder elementEncoder = jag.makeElement();
       elementDesc->encodeJSON( data, elementEncoder );
       data += allocSize;
     }
   }
   elementDesc->disposeDatas( datas, count, allocSize );
 }
Beispiel #11
0
// thread to get input from stdin
void *getInput(void *t){
  ThreadInit *init = t;

  int theCharacter;
  int count = 0;
  while(theCharacter != EOF){
    down(init->bin_sem);
    theCharacter = getchar();
    produce(init->to, &theCharacter);
    count++;
    up(init->bin_sem);
  }

  // lets next buffer know when to stop consuming
  *(init->to->doneInserting) = 1;

  // done, exit thread
  printf("EXIT INPUT\n");
  st_thread_exit(NULL);
}
Beispiel #12
0
void produce() {
  // TODO ensure proper synchronization
  while (items >= MAX_ITEMS) {
	 assert ((items >= 0) && (items <= MAX_ITEMS));
  }
  spinlock_lock(&lock);

  if (items >= MAX_ITEMS) {
	  spinlock_unlock(&lock);
	  producer_wait_count++;
	  assert ((items >= 0) && (items <= MAX_ITEMS));
	  produce();
  } else {
  items++;
  assert ((items >= 0) && (items <= MAX_ITEMS));
  histogram [items] += 1;
  
  spinlock_unlock(&lock);
  }
}
  virtual void allProductsReady() {
    std::vector<QoSCorrections> qosCorrectionsVector =
        Consumer<QoSCorrections>::getConsumables();
    QoSCorrections corrections;

    uint64_t receivedCententionNum = 0;
    for (QoSCorrections product : qosCorrectionsVector) {
      receivedCententionNum += product.size();
      for (slave::QoSCorrection correction : product) {
        if (checkForDuplicates(correction, corrections)) {
          // Filter out duplicated value.
          continue;
        }
        corrections.push_back(correction);
      }
    }

    SERENITY_LOG(INFO) << "Received " << corrections.size() << " corrections";
    produce(corrections);
    return;
  }
Beispiel #14
0
int main(int argc, char const *argv[])
{
	if (argc != 2) {
		fprintf(stderr, "Usage: %s <producer/consumer>\n", argv[0]);
		return -1;
	}

	shm *ptr;
	int fd;

	fd = shm_open("/pc", O_CREAT | O_RDWR, 0777);
	if(fd == -1) handle_error("shm_open");
	
	ptr = mmap(NULL, sizeof(shm), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	if(ptr == MAP_FAILED) handle_error("mmap");

	if(strcmp(argv[1], "producer") == 0) {
		// PRODUCER
		sem_init(&ptr->mutex, 1, 1);
		sem_init(&ptr->empty, 1, BUFFER_SIZE);
		sem_init(&ptr->full, 1, 0);

		if(ftruncate(fd, sizeof(shm)) == -1) handle_error("ftruncate");

		produce(ptr);
	} 
	else if(strcmp(argv[1], "consumer") == 0) {
		// CONSUMER
		consume(ptr);
	}

	shm_unlink("/pc");
	close(fd);

	sem_destroy(&ptr->mutex);
	sem_destroy(&ptr->full);
	sem_destroy(&ptr->empty);
	munmap(ptr, sizeof(*ptr));
	return 0;
}
void PythonConsole::runStatement(const char *statement)
{
	assert(mp_consoleDlg);
	if (mp_consoleDlg)
	{
		mp_consoleDlg->runEnabled(false);
	}

	// Console statements executed whilst a script is in progress MUST run on a separate 
	// thread.  Otherwise, we wait for the GIL, no problem, except that that blocks the UI thread
	// so if the script happens to be sending a message to scintilla (likely), then 
	// it will deadlock.
	// PyProducerConsumer used here to keep one thread running the actual statements

	if (!m_consumerStarted)
	{
		m_consumerStarted = true;
		startConsumer();
	}

	produce(std::shared_ptr<std::string>(new std::string(statement)));
}
Beispiel #16
0
int main (int argc, char *argv[])
{
	int socket_descriptor[2];
	
	socketpair(PF_LOCAL, SOCK_STREAM, 0, socket_descriptor);
	
	int first_child;
	int second_child;
	
	switch (first_child=fork()){
		case 0: close(socket_descriptor[0]); produce(socket_descriptor[1]); break;
		case -1: fprintf(stderr, "What is this? :-("); return 1; break;
		default: 
			switch (second_child=fork()) {
				case 0: close(socket_descriptor[1]); consume(socket_descriptor[0]); break;
				case -1: fprintf(stderr, "What is this? :-(("); return 1; break;
				default: close(socket_descriptor[1]); close(socket_descriptor[0]); wait_and_die(first_child, second_child); break;
			}
		
	}
	return 0;
}
Beispiel #17
0
void *producer (void *arg)
{
    printf ("Starting the producer thread, id=%3d\n",
            (int)pthread_self () % 1000);
    while (j_produced < nmax) {
        pthread_mutex_lock (&lock);
        while (j_active >= nbuf) {
            PRO_CHECK;
            pthread_cond_wait (&cond_not_full, &lock);
        }
        PRO_CHECK;
        j_produced++;
        j_active++;
        printf ("prod %3d, active %3d, id=%3d", j_produced, j_active,
                (int)pthread_self () % 1000);
        produce (j_produced);
        pthread_cond_broadcast (&cond_not_empty);
        pthread_mutex_unlock (&lock);
    }
    PRO_QUIT;

}
Beispiel #18
0
/* the producer function  */
void*
producer(void* arg) {
  /* fill in the details here */
  /* you need to ensure that the function satisfies the
     requirements of the producer/consumer problem */
  int prod_ident = *((int*)arg);
  int i;
  int make_prod;
  for(i=0;i<MAX_ITEM_TO_PRODUCE;++i) {
    /* each producer produces "MAX_ITEM_TO_PRODUCE" and then quit */
    make_prod =  produce(prod_ident, i);
    sem_wait(&fU);
    sem_wait(&eM);
    //after semaphore waits put produced
    enqueue(&fifo_buffer, make_prod);
    //make post to empty and mut
    sem_post(&eM);
    sem_post(&mutex);


  }
  return 0 ;
}
Beispiel #19
0
void run_test(size_t count, std::initializer_list<R*> readers, std::initializer_list<P*> producers)
{
	auto nb_producer = producers.size();
	auto expected_sum = nb_producer * (count*(count-1))/2;
	
	std::vector<std::future<double>> handlers;
	std::vector<std::future<std::pair<double, unsigned long>>> read_handlers;
	for(auto p : producers) 
		handlers.push_back(std::async(std::launch::async, [=](){ return produce(*p, count); }));
	for(auto r : readers) 
		read_handlers.push_back(std::async(std::launch::async, [=](){ return consume(*r, count*nb_producer); }));
	
	std::cout << std::setprecision(2) << "[99.9th.prctl";
	for(auto& r : read_handlers) {
		auto result = r.get();
		auto rl = result.first;
		assertEquals(expected_sum, result.second);
		std::cout << ", r: " << rl << "us";
	}
	for(auto& p : handlers)
		std::cout << ", p: " << p.get() << "us";
	std::cout << "]";
}
Beispiel #20
0
    void work(void)
    {
        //number of elements to work with
        auto elems = this->workInfo().minElements;
        if (elems == 0) return;

        //get pointers to in and out buffer
        auto inPort = this->input(0);
        auto outPort = this->output(0);
        auto in = inPort->buffer().template as<const InType *>();
        auto out = outPort->buffer().template as<OutType *>();

        //compute angle using templated function
        const size_t N = elems*inPort->dtype().dimension();
        for (size_t i = 0; i < N; i++)
        {
            out[i] = getAngle(in[i]);
        }

        //produce and consume on 0th ports
        inPort->consume(elems);
        outPort->produce(elems);
    }
int main()
{
	
	int pipe1[2];
	pid_t pid;
	
	if (pipe(pipe1) < 0)
	{
		printf ("Pipe didn't create\n");
		exit (-1);
	}
	else
	{
		if ((pid = fork()) == (pid_t)0)
		{
			close(pipe1[1]);
				
			consumer (pipe1[0]);

			//close(pipe1[0]);
		}
		else if (pid > 0)
		{
			close(pipe1[0]);
				
			produce (pipe1[1]);
			//close(pipe1[1]);
		
		}
		else
		{
			printf("Process can not fork\n");
			exit(-1);
		}
		return 0;
	}
}
Beispiel #22
0
    void work(void)
    {
        auto inPort = this->input(0);
        auto outPort = this->output(0);
        inPort->setReserve(_reserveBytes);

        //handle packet conversion if applicable
        if (inPort->hasMessage())
        {
            auto msg = inPort->popMessage();
            if (msg.type() == typeid(Pothos::Packet))
                this->msgWork(msg.extract<Pothos::Packet>());
            else outPort->postMessage(msg);
            return; //output buffer used, return now
        }

        //calculate work size given reserve requirements
        const size_t numInBytes = (inPort->elements()/_reserveBytes)*_reserveBytes;
        const size_t reserveSyms = (_reserveBytes*8)/_mod;
        const size_t numOutSyms = (outPort->elements()/reserveSyms)*reserveSyms;
        const size_t numBytes = std::min((numOutSyms*_mod)/8, numInBytes);
        if (numBytes == 0) return;

        //perform conversion
        auto in = inPort->buffer().as<const unsigned char *>();
        auto out = outPort->buffer().as<unsigned char *>();
        switch (_order)
        {
        case MSBit: ::bytesToSymbolsMSBit(_mod, in, out, numBytes); break;
        case LSBit: ::bytesToSymbolsLSBit(_mod, in, out, numBytes); break;
        }

        //consume input bytes and output symbols
        inPort->consume(numBytes);
        outPort->produce((numBytes*8)/_mod);
    }
    virtual Try<Nothing> syncConsume(
        const std::vector<QoSCorrections> products) {
        QoSCorrections corrections;

        uint64_t receivedCententionNum = 0;
        for (QoSCorrections product : products) {
            receivedCententionNum += product.size();
            for (slave::QoSCorrection correction : product) {
                if (checkForDuplicates(correction, corrections)) {
                    // Filter out duplicated value.
                    continue;
                }

                corrections.push_back(correction);
            }
        }

        SERENITY_LOG(INFO) << "Received " << receivedCententionNum << " corrections"
                           << " and merged to " << corrections.size() << " corrections.";

        produce(corrections);

        return Nothing();
    }
Beispiel #24
0
/*
 * Produce for a specific nation
 */
void
produce_sect(int natnum, int etu, struct bp *bp, int p_sect[][2])
{
    struct sctstr *sp;
    struct natstr *np;
    short buf[I_MAX + 1];
    short *vec;
    int work, cost, ecost, pcost, sctwork;
    int n, desig, neweff, amount;

    for (n = 0; NULL != (sp = getsectid(n)); n++) {
	if (sp->sct_type == SCT_WATER)
	    continue;
	if (sp->sct_own != natnum)
	    continue;
	if (sp->sct_updated != 0)
	    continue;

	np = getnatp(natnum);

	if (player->simulation) {
	    /* work on a copy, which will be discarded */
	    memcpy(buf, sp->sct_item, sizeof(buf));
	    vec = buf;
	} else
	    vec = sp->sct_item;

	/* If everybody is dead, the sector reverts to unowned.
	 * This is also checked at the end of the production in
	 * they all starved or were plagued off.
	 */
	if (vec[I_CIVIL] == 0 && vec[I_MILIT] == 0 &&
	    !has_units(sp->sct_x, sp->sct_y, sp->sct_own, NULL)) {
	    if (!player->simulation) {
		makelost(EF_SECTOR, sp->sct_own, 0, sp->sct_x, sp->sct_y);
		sp->sct_own = 0;
		sp->sct_oldown = 0;
	    }
	    continue;
	}

	sp->sct_updated = 1;
	work = 0;

	sctwork = do_feed(sp, np, vec, &work, etu);
	bp_put_items(bp, sp, vec);

	if (sp->sct_off || np->nat_money < 0)
	    continue;

	neweff = sp->sct_effic;
	amount = 0;
	pcost = cost = ecost = 0;

	desig = sp->sct_type;

	if (dchr[desig].d_maint) {
	    cost = etu * dchr[desig].d_maint;
	    p_sect[SCT_MAINT][0]++;
	    p_sect[SCT_MAINT][1] += cost;
	    if (!player->simulation)
		np->nat_money -= cost;
	}

	if ((sp->sct_effic < 100 || sp->sct_type != sp->sct_newtype) &&
	    np->nat_money >= 0) {
	    neweff = upd_buildeff(np, sp, &work, vec, etu, &desig, sctwork,
				  &cost);
	    bp_put_items(bp, sp, vec);
	    p_sect[SCT_EFFIC][0]++;
	    p_sect[SCT_EFFIC][1] += cost;
	    if (!player->simulation) {
		np->nat_money -= cost;
		sp->sct_type = desig;
		sp->sct_effic = neweff;
	    }
	}

	if (desig == SCT_ENLIST && neweff >= 60 &&
	    sp->sct_own == sp->sct_oldown) {
	    p_sect[desig][0] += enlist(vec, etu, &ecost);
	    p_sect[desig][1] += ecost;
	    if (!player->simulation)
		np->nat_money -= ecost;
	    bp_put_items(bp, sp, vec);
	}

	/*
	 * now do the production (if sector effic >= 60%)
	 */

	if (neweff >= 60) {
	    if (np->nat_money >= 0 && dchr[desig].d_prd >= 0)
		work -= produce(np, sp, vec, work, desig, neweff,
				&pcost, &amount);
	    bp_put_items(bp, sp, vec);
	}

	bp_put_avail(bp, sp, work);
	p_sect[desig][0] += amount;
	p_sect[desig][1] += pcost;
	if (!player->simulation) {
	    sp->sct_avail = work;
	    np->nat_money -= pcost;
	}
    }
}
Beispiel #25
0
void* producer() {
  for (int i=0; i < NUM_ITERATIONS; i++)
    produce();
}
Beispiel #26
0
void* producer() {
  for (int i=0; i < NUM_ITERATIONS; i++)
    produce();
  return NULL;
}
Beispiel #27
0
void
user_move (void)
{
	int i, sec, sec_start;
	piece_type_t n;
	piece_info_t *obj, *next_obj;
	int prod;

	/*
	 * First we loop through objects to update the user's view
	 * of the world and perform any other necessary processing.
	 * We would like to have the world view up to date before
	 * asking the user any questions.  This means that we should
	 * also scan through all cities before possibly asking the
	 * user what to produce in each city.
	 */

	for (n = FIRST_OBJECT; n < NUM_OBJECTS; n++)
		for (obj = user_obj[n]; obj != NULL; obj = obj->piece_link.next)
		{
			obj->moved = 0; /* nothing moved yet */
			scan (user_map, obj->loc); /* refresh user's view of world */
		}

	/* produce new hardware */
	for (i = 0; i < NUM_CITY; i++)
	    if (city[i].owner == USER) {
		scan (user_map, city[i].loc);
		prod = city[i].prod;

		if (prod == NOPIECE)
		{
			/* need production? */
			set_prod (&(city[i])); /* ask user what to produce */
		}
		else if (city[i].work++ >= (long)piece_attr[prod].build_time)
		{
			info("City at %d has completed %s.", city[i].loc, piece_attr[prod].article);
			produce (&city[i]);
			/* produce should set object.moved to 0 */
		}
	}

	/* move all satellites */
	for (obj = user_obj[SATELLITE]; obj != NULL; obj = next_obj) {
		next_obj = obj->piece_link.next;
		move_sat (obj);
	}

	sec_start = cur_sector (); /* get currently displayed sector */
	if (sec_start == -1) sec_start = 0;

	/* loop through sectors, moving every piece in the sector */
	for (i = sec_start; i < sec_start + NUM_SECTORS; i++)
	{
		sec = i % NUM_SECTORS;
		sector_change (); /* allow screen to be redrawn */

		for (n = FIRST_OBJECT; n < NUM_OBJECTS; n++) /* loop through obj lists */
			for (obj = user_obj[move_order[n]]; obj != NULL; obj = next_obj)
			{
				/* loop through objs in list */
				next_obj = obj->piece_link.next;

				if (!obj->moved) /* object not moved yet? */
					if (loc_sector (obj->loc) == sec) /* object in sector? */
						piece_move (obj); /* yup; move the object */
			}
			if (cur_sector() == sec)
			{
				/* is sector displayed? */
				print_sector_u (sec); /* make screen up-to-date */
			}
	}
	if (save_movie) save_movie_screen ();
}
Beispiel #28
0
//thread to change asterisks to carats
void *asterisksToCarat(void *t){
  ThreadInit *init = t;
  char theCharacter;
  char nextCharacter;
  char carat = '^'; //used for produce() if it needs a carat
  int toBreak = 0;

  while(toBreak == 0) {
    //if from is done inserting and there are no elements, break
    down(init->from_bin_sem);

    //printf("ast. done inserting?[%d]\n", *(init->from->doneInserting));
    //printf("ast. numElements?[%d]\n", *(init->from->numElements));

    if( *(init->from->doneInserting) == 1){
      if( (*init->from->numElements == 0))
        toBreak = 1;
    }

    if (toBreak == 0){ 
      up(init->from_bin_sem);
      theCharacter = consume(init->from);
      if (theCharacter == '*'){
        nextCharacter = consume(init->from);
        if (nextCharacter == '*'){ // if two successive asterisks
          printf("producing: [%c]\n", carat);
          down(init->to_bin_sem);
          produce(init->to, &carat);
        }
        else { // if they're not both asterisks
          down(init->to_bin_sem);
          printf("producing: [%c]\n", theCharacter);
          produce(init->to, &theCharacter);
          printf("producing: [%c]\n", nextCharacter);
          produce(init->to, &nextCharacter); 
        }
      }
      else { //the character was not an asterisk
        down(init->to_bin_sem);
printf("ast. producing: [%c]\n", theCharacter);
        produce(init->to, &theCharacter);
        //pretty sure produce context switches to waiting print func.
        //so this is always 0, even though it's being updated right
printf("elems. after ast. produce: [%d]\n", *(init->to->numElements));
      }
      up(init->to_bin_sem);
    }
    up(init->from_bin_sem);
  }

  // lets next buffer know when to stop consuming

  down(init->to_bin_sem);
  *(init->to->doneInserting) = 1;
  up(init->to_bin_sem);

  char theNull = '\0';
  produce(init->to, &theNull);

  // done, exit thread
  printf("EXIT ASTERISK\n");
  st_thread_exit(NULL);
}
/*
void ScintillaWrapper::addText(str s)
{
	const char *raw = extract<const char*>(s);
	call(SCI_ADDTEXT, len(s), reinterpret_cast<LPARAM>(raw));
}


void ScintillaWrapper::AddStyledText(ScintillaCells s)
{
	call(SCI_ADDSTYLEDTEXT, s.length(), reinterpret_cast<LPARAM>(s.cells()));
}

str ScintillaWrapper::getLine(int lineNumber)
{
	int resultLength = call(SCI_GETLINE, lineNumber, NULL);
	char * result = (char *)malloc(resultLength + 1);
	call(SCI_GETLINE, lineNumber, reinterpret_cast<LPARAM>(result));
	result[resultLength] = '\0';
	str o = str((const char *)result);
	free(result);
	return o;
}
*/
void ScintillaWrapper::notify(SCNotification *notifyCode)
{
	if (!m_notificationsEnabled)
		return;

	std::pair<callbackT::iterator, callbackT::iterator> callbackIter 
		= m_callbacks.equal_range(notifyCode->nmhdr.code);
	
	if (callbackIter.first != callbackIter.second)
	{
		std::shared_ptr<CallbackExecArgs> args(new CallbackExecArgs());

		// Create the parameters for the callback
		args->params["code"] = notifyCode->nmhdr.code;

		
		switch(notifyCode->nmhdr.code)
		{
			
			case SCN_STYLENEEDED:
				args->params["position"] = notifyCode->position;
				break;

			case SCN_CHARADDED:
				args->params["ch"] = notifyCode->ch;
				break;

			case SCN_SAVEPOINTREACHED:
				break;

			case SCN_SAVEPOINTLEFT:
				break;

			case SCN_MODIFYATTEMPTRO:
				break;

			case SCN_KEY:
				args->params["ch"] = notifyCode->ch;
				args->params["modifiers"] = notifyCode->modifiers;
				break;

			case SCN_DOUBLECLICK:
				args->params["position"] = notifyCode->position;
				args->params["modifiers"] = notifyCode->modifiers;
				args->params["line"] = notifyCode->line;
				break;

			case SCN_UPDATEUI:
				break;

			case SCN_MODIFIED:
				args->params["position"] = notifyCode->position;
				args->params["modificationType"] = notifyCode->modificationType;
				args->params["text"] = notifyCode->text;
				args->params["length"] = notifyCode->length;
				args->params["linesAdded"] = notifyCode->linesAdded;
				args->params["line"] = notifyCode->line;
				args->params["foldLevelNow"] = notifyCode->foldLevelNow;
				args->params["foldLevelPrev"] = notifyCode->foldLevelPrev;
				if (notifyCode->modificationType & SC_MOD_CHANGEANNOTATION)
				{
					args->params["annotationLinesAdded"] = notifyCode->annotationLinesAdded;
				}
				if (notifyCode->modificationType & SC_MOD_CONTAINER)
				{
					args->params["token"] = notifyCode->token;
				}

				
				break;

			case SCN_MACRORECORD:
				args->params["message"] = notifyCode->message;
				args->params["wParam"] = notifyCode->wParam;
				args->params["lParam"] = notifyCode->lParam;
				break;

			case SCN_MARGINCLICK:
				args->params["margin"] = notifyCode->margin;
				break;

			case SCN_NEEDSHOWN:
				break;

			case SCN_PAINTED:
				break;

			case SCN_USERLISTSELECTION:
				args->params["text"] = notifyCode->text;
				args->params["listType"] = notifyCode->listType;
				break;

			case SCN_URIDROPPED:
				break;

			case SCN_DWELLSTART:
				args->params["position"] = notifyCode->position;
				args->params["x"] = notifyCode->x;
				args->params["y"] = notifyCode->y;
				break;

			case SCN_DWELLEND:
				args->params["position"] = notifyCode->position;
				args->params["x"] = notifyCode->x;
				args->params["y"] = notifyCode->y;
				break;

			case SCN_ZOOM:
				break;

			case SCN_HOTSPOTCLICK:
			case SCN_HOTSPOTDOUBLECLICK:
			case SCN_HOTSPOTRELEASECLICK:
				args->params["position"] = notifyCode->position;
				args->params["modifiers"] = notifyCode->modifiers;
				break;

			case SCN_INDICATORCLICK:
				break;

			case SCN_INDICATORRELEASE:
				break;

			case SCN_CALLTIPCLICK:
				args->params["position"] = notifyCode->position;
				break;

			case SCN_AUTOCSELECTION:
				args->params["text"] = notifyCode->text;
				break;

			case SCN_AUTOCCANCELLED:
				break;

			case SCN_AUTOCCHARDELETED:
				break;
		
		default:
			// Unknown notification, so just fill in all the parameters.
			args->params["idFrom"] = notifyCode->nmhdr.idFrom;
			args->params["hwndFrom"] = notifyCode->nmhdr.hwndFrom;
			args->params["position"] = notifyCode->position;
			args->params["modificationType"] = notifyCode->modificationType;
			args->params["text"] = notifyCode->text;
			args->params["length"] = notifyCode->length;
			args->params["linesAdded"] = notifyCode->linesAdded;
			args->params["line"] = notifyCode->line;
			args->params["foldLevelNow"] = notifyCode->foldLevelNow;
			args->params["foldLevelPrev"] = notifyCode->foldLevelPrev;
			args->params["annotationLinesAdded"] = notifyCode->annotationLinesAdded;
			args->params["listType"] = notifyCode->listType;
			args->params["message"] = notifyCode->message;
			args->params["wParam"] = notifyCode->wParam;
			args->params["lParam"] = notifyCode->lParam;
			args->params["modifiers"] = notifyCode->modifiers;
			args->params["token"] = notifyCode->token;
			args->params["x"] = notifyCode->x;
			args->params["y"] = notifyCode->y;
			break;
		}

		while (callbackIter.first != callbackIter.second)
		{
			args->callbacks.push_back(callbackIter.first->second);		
			++callbackIter.first;
		}

		produce(args);
	}
}
Beispiel #30
0
 void ArrayProducer::ComputeState::produce( void *data ) const
 {
   produce( 0, m_count, data );
 }