void prodCons(struct storage *sFarsz, struct storage *sCiasto, struct storage *sPierogi, int microSecPeriod) { int prior; while (1) { /// get farsz and ciasto if(consumer(sFarsz, 0) == 1) { prior = 1; } else prior = 0; consumer(sCiasto, 0); /// production time usleep(microSecPeriod); /// insert pieroga if(prior == 1) { priorProducer(sPierogi, 0); } else producer(sPierogi, 0); } }
int main(int argc ,char **argv) { if(pipe(pipe_fd) < 0) { printf("Pipe creat error"); exit(-1); } else { puts("Pipe is created successfully!"); if((pid1 =fork())==0) producer(1); if((pid2 =fork())==0) producer(2); if((pid3 =fork())==0) consumer(1); if((pid4 =fork())==0) consumer(2); } close(pipe_fd[0]); close(pipe_fd[1]); int i,pid,status; for(i=0;i<4;i++) pid=wait(&status); exit(0); }
Pass::Status PassManager::Run(IRContext* context) { auto status = Pass::Status::SuccessWithoutChange; // If print_all_stream_ is not null, prints the disassembly of the module // to that stream, with the given preamble and optionally the pass name. auto print_disassembly = [&context, this](const char* preamble, Pass* pass) { if (print_all_stream_) { std::vector<uint32_t> binary; context->module()->ToBinary(&binary, false); SpirvTools t(SPV_ENV_UNIVERSAL_1_2); std::string disassembly; t.Disassemble(binary, &disassembly, 0); *print_all_stream_ << preamble << (pass ? pass->name() : "") << "\n" << disassembly << std::endl; } }; SPIRV_TIMER_DESCRIPTION(time_report_stream_, /* measure_mem_usage = */ true); for (auto& pass : passes_) { print_disassembly("; IR before pass ", pass.get()); SPIRV_TIMER_SCOPED(time_report_stream_, (pass ? pass->name() : ""), true); const auto one_status = pass->Run(context); if (one_status == Pass::Status::Failure) return one_status; if (one_status == Pass::Status::SuccessWithChange) status = one_status; if (validate_after_all_) { spvtools::SpirvTools tools(target_env_); tools.SetMessageConsumer(consumer()); std::vector<uint32_t> binary; context->module()->ToBinary(&binary, true); if (!tools.Validate(binary.data(), binary.size(), val_options_)) { std::string msg = "Validation failed after pass "; msg += pass->name(); spv_position_t null_pos{0, 0, 0}; consumer()(SPV_MSG_INTERNAL_ERROR, "", null_pos, msg.c_str()); return Pass::Status::Failure; } } // Reset the pass to free any memory used by the pass. pass.reset(nullptr); } print_disassembly("; IR after last pass", nullptr); // Set the Id bound in the header in case a pass forgot to do so. // // TODO(dnovillo): This should be unnecessary and automatically maintained by // the IRContext. if (status == Pass::Status::SuccessWithChange) { context->module()->SetIdBound(context->module()->ComputeIdBound()); } passes_.clear(); return status; }
int main() {int l=3; int k; while(l) {printf("\nEnter what you wanna do\n0.Exit\t1.Produce\t2.Consume\n"); scanf("%d",&l); switch(l) {case 1:while(1) { pr=1; if(producer()==1) printf("\nItem produced"); printf("\nProduce one more:1.Yes\t:"); scanf("%d",&k); if(k==1) continue; prod=-1; callp=-1; if(callc!=-1||cons!=0) consumer(); prod=0; if(k!=1) break; } break; case 2:while(1) { cs=1; if(consumer()==1) printf("\nItem consumption process over"); printf("\nConsume one more:1.Yes\t:"); scanf("%d",&k); if(k==1) continue; callc=-1; cons=-1; if(callp!=-1||prod!=0) producer(); cons=0; if(k!=1) break; } break; } } return 0; }
int switchtoconsumer() { int sw; if(callp==-1) callp=0; printf("\nDo you wanna switch to consume : 1.Yes\t2.No:"); scanf("%d",&sw); if(sw==1) {if(callp==1) { callc=0; return 1;} else { callp=1; if(callc==1) return 1; else { if(cs==0) cs=1; consumer(); } } } return 0; }
int main(int argc, char *argv[]) { srand(time(NULL)); int i, fd, result; int *file_memory; pid_t child; child = fork(); char* program = "./MemMapConsum";; char* arglist[] = {"./MemMapConsum", "MemMapConsum", NULL} ; fd = open(FILEPATH, O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600); lseek(fd, FILE_LENGTH+1, SEEK_SET); write(fd, "", 1); file_memory = (int*)mmap(0, FILE_LENGTH, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if(child == 0){ for (i = 1; i <=N; ++i) { file_memory[i] = produce_item(); } } else { wait(); execvp(program, arglist); consumer(); } close(fd); munmap(file_memory, FILE_LENGTH); return 0; }
int main() { mqd_t qid; struct mq_attr attr; char* qname="/msgq"; /*队列的名字*/ memset(&attr,0,sizeof(attr)); attr.mq_maxmsg=5; attr.mq_msgsize=MSGSIZE; qid=mq_open(qname,O_CREAT|O_RDWR,0666,&attr); /*创建队列*/ if(qid<0){ perror("mq_open"); return -1; } if(!fork()){ producer(qid); exit(0); } wait(NULL); consumer(qid); mq_unlink(qname); return 0; }
void fifo_test(Buffer* buffer) { // Start of timing. boost::timer::auto_cpu_timer progress; // Initialize the buffer with some values before launching producer and consumer threads. for (unsigned long i = queue_size / 2L; i > 0; --i) { #if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x581)) buffer->push_front(Buffer::value_type()); #else buffer->push_front(BOOST_DEDUCED_TYPENAME Buffer::value_type()); #endif } // Construct the threads. Consumer<Buffer> consumer(buffer); Producer<Buffer> producer(buffer); // Start the threads. boost::thread consume(consumer); boost::thread produce(producer); // Wait for completion. consume.join(); produce.join(); // End of timing. // destructor of boost::timer::auto_cpu_timer will output the time to std::cout. }
int main(int /*argc*/, char ** /*argv*/) { PoorMockSecondEdition mock; MOCKPP_STD_NS::cout << "Tests starting" << MOCKPP_STD_NS::endl; MOCKPP_TRY { // Run Consumer object Consumer consumer(&mock); mock.open_counter.setExpected(1); mock.read_counter.setExpected(4); mock.close_counter.setExpected(5); consumer.load(); mock.verify(); consumer.process(); mock.open_counter.setExpected(6); mock.write_counter.setExpected(9); mock.close_counter.setExpected(10); consumer.save(); mock.verify(); MOCKPP_STD_NS::cout << "Tests finished" << MOCKPP_STD_NS::endl; } MOCKPP_CATCH(MOCKPP_STD_NS::exception &ex) { #ifndef MOCKPP_NO_EXCEPTIONS MOCKPP_STD_NS::cout << MOCKPP_STD_NS::endl << "Error occured.\n" << ex.what() << MOCKPP_STD_NS::endl << MOCKPP_STD_NS::endl; #endif return 1; }
status_t ServerFont::GetBoundingBoxesForStrings(char *charArray[], int32 lengthArray[], int32 numStrings, BRect rectArray[], font_metric_mode mode, escapement_delta deltaArray[]) { // TODO: The font_metric_mode is never used if (!charArray || !lengthArray|| numStrings <= 0 || !rectArray || !deltaArray) return B_BAD_DATA; Transformable transform(EmbeddedTransformation()); for (int32 i = 0; i < numStrings; i++) { int32 numBytes = lengthArray[i]; const char* string = charArray[i]; escapement_delta delta = deltaArray[i]; BoundingBoxConsumer consumer(transform, NULL, true); if (!GlyphLayoutEngine::LayoutGlyphs(consumer, *this, string, numBytes, &delta, fSpacing)) { return B_ERROR; } rectArray[i] = consumer.stringBoundingBox; } return B_OK; }
void test_intermittent() { sc::blocking_queue<MyMovableStr> queue{}; std::thread producer([&] { TestStringGenerator gen{}; for (size_t i = 0; i < 10; i++) { std::string str = gen.generate(42); queue.emplace(std::move(str)); } std::this_thread::sleep_for(std::chrono::milliseconds{200}); for (size_t i = 10; i < 20; i++) { std::string str = gen.generate(42); queue.emplace(std::move(str)); } std::this_thread::sleep_for(std::chrono::milliseconds{300}); for (size_t i = 20; i < ELEMENTS_COUNT; i++) { std::string str = gen.generate(42); queue.emplace(std::move(str)); } }); std::thread consumer([&] { for (size_t i = 0; i < ELEMENTS_COUNT; i++) { MyMovableStr el{""}; bool success = queue.take(el); slassert(success); slassert(42 == el.get_val().size()); } }); producer.join(); consumer.join(); }
int main (int argc, char** argv) { int buff_size = BUFFER_SIZE; if (argc == 2) { buff_size = atoi (argv[1]); std::cout << "Setting buffer size to " << buff_size << " frames " << std::endl; } else { std::cout << "Using default buffer size of " << buff_size << " frames " << std::endl; } buff.setCapacity (buff_size); std::cout << "Starting the producer and consumer threads..." << std::endl; std::cout << "Press Ctrl-C to end" << std::endl; boost::thread producer (grabAndSend); boost::this_thread::sleep (boost::posix_time::seconds (2)); boost::thread consumer (receiveAndProcess); boost::thread consumer2 (receiveAndProcess); boost::thread consumer3 (receiveAndProcess); signal (SIGINT, ctrlC); producer.join (); { boost::mutex::scoped_lock io_lock (io_mutex); PCL_WARN ("Producer done\n"); } consumer.join (); consumer2.join(); consumer3.join(); PCL_WARN ("Consumers done\n"); return (0); }
bool pop(U & ret) { BOOST_STATIC_ASSERT((lslboost::is_convertible<T, U>::value)); detail::consume_via_copy<U> consumer(ret); return consume_one(consumer); }
int main(int argc, char *argv[]) { int fds[2] = {0}; int th = 0; int ret = pipe(fds); if (ret < 0) { printf("pipe failed\n"); return -1; } th = fork(); if (th < 0) { printf("fork failed\n"); return -1; } else if (th == 0) { product(fds); } else { consumer(fds); } wait(NULL); return 0; }
void TestConcurrentLockingQueue::testConcurrentLockingQueueExhibitsCorrectBehaviourInMultiProducerSetting(void) { const size_t length = 2000; const size_t producerThreadCount = 4; std::vector<size_t> resVec; ConcurrentLockingQueue<size_t> queue; size_t expectedVecLength = 0; std::vector<std::thread> producerPool; for (size_t i = 0; i < producerThreadCount; i++) { producerPool.push_back(std::thread(produce, &queue, length)); } expectedVecLength = length*producerPool.size(); std::thread consumer(consume, &resVec, &queue, expectedVecLength); for (size_t i = 0; i < producerPool.size(); i++) { producerPool[i].join(); } consumer.join(); //check size CPPUNIT_ASSERT(expectedVecLength == resVec.size()); std::sort(resVec.begin(), resVec.end()); // check if all values are in vector now for (size_t i = 0; i < length; i++) { for (size_t j = 0; j < producerThreadCount; j++) { CPPUNIT_ASSERT(i == resVec[i*producerThreadCount + j]); } } }
int main() { boost::thread producer(product); boost::thread consumer(consume); producer.join(); consumer.join(); }
void consumer_thread(struct buffer *b) //@ : thread_run //@ requires thread_run_data(consumer_thread)(?tobs,b) &*& obs(tobs); //@ ensures obs(nil); { //@ open thread_run_data(consumer_thread)(_,_); consumer(b); }
ideal FrbAlexanderDual(const ideal& I, ConstRefPPMonoidElem pp) { MustHaveMonomialGens(I, "FrbAlexanderDual"); const SparsePolyRing polyRing = RingOf(I); if (PPM(polyRing) != owner(pp)) CoCoA_ERROR(ERR::MixedPPMs, "FrbAlexanderDual"); const std::size_t count = NumIndets(polyRing); Frobby::Ideal frobbyIdeal(count); ToFrobbyIdeal(frobbyIdeal, I); FrobbyMonomialIdealConsumer consumer(polyRing); // Set up the point to dualize on. WrappedMpzT* exponentVector = new WrappedMpzT[count]; try { for (size_t indep = 0; indep < count; ++indep) mpz_set(exponentVector[indep].getMpzT(), mpzref(BigExponent(pp, indep))); // Compute Alexander dual using Frobby. Frobby::alexanderDual(frobbyIdeal, (mpz_t*)exponentVector, consumer); } catch (...) { delete[] exponentVector; throw; } delete[] exponentVector; return consumer.getIdealsRef().back(); }
ImageTargetFileQuartz::ImageTargetFileQuartz( DataTargetRef dataTarget, ImageSourceRef imageSource, ImageTarget::Options options, const std::string &extensionData ) : cocoa::ImageTargetCgImage( imageSource, options ) { cocoa::SafeCfString uti = cocoa::createSafeCfString( extensionData ); mImageDest = NULL; if( dataTarget->providesFilePath() ) { cocoa::SafeCfString pathString = cocoa::createSafeCfString( dataTarget->getFilePath().string() ); const std::shared_ptr<__CFURL> urlRef( (__CFURL*)::CFURLCreateWithFileSystemPath( kCFAllocatorDefault, pathString.get(), kCFURLPOSIXPathStyle, false ), cocoa::safeCfRelease ); mImageDest = ::CGImageDestinationCreateWithURL( urlRef.get(), uti.get(), 1, NULL ); } else if( dataTarget->providesUrl() ) { std::shared_ptr<__CFURL> urlRef( (__CFURL*)cocoa::createCfUrl( dataTarget->getUrl() ), cocoa::safeCfRelease ); mImageDest = ::CGImageDestinationCreateWithURL( urlRef.get(), uti.get(), 1, NULL ); } else { // we'll wrap a cinder::OStream in a CGDataConsumer for output OStreamRef *ostreamRef = new OStreamRef( dataTarget->getStream() ); ::CGDataConsumerCallbacks callbacks; callbacks.putBytes = cgDataConsumerPutBytes; callbacks.releaseConsumer = cgDataConsumerRelease; std::shared_ptr<CGDataConsumer> consumer( ::CGDataConsumerCreate( ostreamRef, &callbacks ), ::CGDataConsumerRelease ); mImageDest = ::CGImageDestinationCreateWithDataConsumer( consumer.get(), uti.get(), 1, NULL ); } if( ! mImageDest ) throw ImageIoExceptionFailedWrite(); setupImageDestOptions( options ); }
int main() //@ requires true; //@ ensures result == 55; { //@ int id_text = create_ghost_cell({1,2,3,4,5,6,7,8,9,10}); //@ leak ghost_cell(id_text, _); struct buffer *buffer = create_buffer(2); if (buffer == 0){ abort(); } //@ assert buffer(_, _, ?id_read, ?id_write); //@ create_ops(id_text, id_write); //@ create_ops(id_text, id_read); //@ close thread_run_pre(producer)(buffer, thread_data(id_text, id_read, id_write, 0, 10)); struct thread *thread = thread_start_joinable(producer, buffer); int result = consumer(buffer, 100); thread_join(thread); //@ open thread_run_post(producer)(buffer, _); return result; //@ leak exists(_); //@ leak token(_, _); //@ leak token(_, _); //@ leak [1/2]buffer(_, _, _, _); //@ leak [1/2]buffer(_, _, _, _); }
void* producer(void* ptr) { int item; while (TRUE) { item = produce_item(); // generate next item if (count == N) { // call consumer if buffer is full consumer(&ptr); } insert_item(item); // put item in buffer count = count + 1; // increment count of items in buffer if (count == 1) { // call consumer if buffer size == 1 consumer(&ptr); } } return NULL; }
int main() { vec.reserve(BUFFER_SIZE*2); std::thread producer(produce), consumer(consume); producer.join(); // Produce some more producer = std::thread(produce); producer.join(); // Produce A LOT more std::vector<std::thread> many_producers(8); for (auto&& t : many_producers) { t = std::thread(produce); } for (auto && t : many_producers) { t.join(); } // Tell consumer we are done producing { std::lock_guard<std::mutex> lock(mu); done = true; } empty.notify_one(); consumer.join(); }
void test_take_wait() { sc::blocking_queue<MyMovableStr> queue{}; std::thread producer([&queue] { std::this_thread::sleep_for(std::chrono::milliseconds{200}); queue.emplace("aaa"); std::this_thread::sleep_for(std::chrono::milliseconds{200}); queue.emplace("bbb"); }); std::thread consumer([&queue] { // not yet available MyMovableStr el1{""}; bool success1 = queue.take(el1, 100); slassert(!success1); slassert("" == el1.get_val()); // first received MyMovableStr el2{""}; bool success2 = queue.take(el2, 150); slassert(success2); slassert("aaa" == el2.get_val()); // wait for next std::this_thread::sleep_for(std::chrono::milliseconds{200}); // should be already there MyMovableStr el3{""}; bool success3 = queue.take(el3, 10); slassert(success3); slassert("bbb" == el3.get_val()); }); producer.join(); consumer.join(); }
int main(void) { int pid; /* Inicializo rand */ srand(time(NULL)); sem_init(&s_empty, 0, ITEMS); sem_init(&s_full, 0, 0); printf("s_empty = %d\n", s_empty); printf("s_full = %d\n", s_full); /* Genero los procesos consumidor y productor */ if ((pid = fork()) == -1) exit(EXIT_FAILURE); else if (pid == 0) /* Proceso hijo - Consumidor */ consumer(); else { /* Proceso padre - Productor */ producer(); /* Espero a mi hijo */ wait(NULL); sem_destroy(&s_empty); sem_destroy(&s_full); } return 0; }
status_t ServerFont::GetEdges(const char* string, int32 numBytes, edge_info* edges) const { if (!string || numBytes <= 0 || !edges) return B_BAD_DATA; EdgesConsumer consumer(edges, fSize); if (GlyphLayoutEngine::LayoutGlyphs(consumer, *this, string, numBytes, NULL, fSpacing)) { return B_OK; } return B_ERROR; // FT_Face face = GetTransformedFace(false, false); // if (!face) // return B_ERROR; // // const char *string = charArray; // for (int i = 0; i < numChars; i++) { // FT_Load_Char(face, UTF8ToCharCode(&string), FT_LOAD_NO_BITMAP); // edgeArray[i].left = float(face->glyph->metrics.horiBearingX) // / 64 / fSize; // edgeArray[i].right = float(face->glyph->metrics.horiBearingX // + face->glyph->metrics.width - face->glyph->metrics.horiAdvance) // / 64 / fSize; // } // // PutTransformedFace(face); // return B_OK; }
int main(void) { unsigned int count; pid_t pid = ONE; pid_t pids[NO_OF_CHILDREN]; init(); shm(); for(count = 0; count < NO_OF_CHILDREN; count++) { if (pid) { if ((pid = fork()) < 0) { fprintf(stderr, "The fork() function has failed: %s", strerror(errno)); return EXIT_FAILURE; } pids[count] = pid; if (pid) fprintf(stderr, "%d # Created pid process: %d\n", getpid(), (pids[count])); } else break; } if (!pid) { fprintf(stderr, "Child %i started...\n", count); if (count <= 4) { fprintf(stderr, "+1 producer!\n"); producer(count, g_letters_and_numbers); exit(EXIT_SUCCESS); } else { fprintf(stderr, "+1 consumer!\n"); consumer(count, g_letters_and_numbers); exit(EXIT_SUCCESS); } } else { usleep(WAIT_CHILDREN); printf(NEW_LINE); for (count = 0; count < NO_OF_CHILDREN; count++) { kill(pids[count], SIGKILL); fprintf(stderr, "%d # Killing pid process: %d\n", getpid(), pids[count]); } end(); } exit(EXIT_SUCCESS); }
virtual void random_transaction(thread_args_t* args, unsigned int* seed, unsigned int val, int chance) { // am I a producer thread? if (args->id < m_producers) { unsigned int j = val % m_max; int action = chance; if (action < BMCONFIG.lookupPct) { if (lookup(j)) { ++args->count[TXN_LOOKUP_TRUE]; } else { ++args->count[TXN_LOOKUP_FALSE]; } } else if (action < BMCONFIG.insertPct) { insert(j); ++args->count[TXN_INSERT]; } else { remove(j); ++args->count[TXN_REMOVE]; } } else { consumer(); } }
void fifo_test(Buffer* buffer) { // Start of measurement boost::progress_timer progress; // Initialize the buffer with some values before launching producer and consumer threads. for (unsigned long i = QUEUE_SIZE / 2L; i > 0; --i) { #if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x581)) buffer->push_front(Buffer::value_type()); #else buffer->push_front(BOOST_DEDUCED_TYPENAME Buffer::value_type()); #endif } Consumer<Buffer> consumer(buffer); Producer<Buffer> producer(buffer); // Start the threads. boost::thread consume(consumer); boost::thread produce(producer); // Wait for completion. consume.join(); produce.join(); // End of measurement }
void producer_consumer_sample() { putchar('\n'); puts(__FUNCTION__); putchar('\n'); consumer(RfNew Coroutine(boost::bind(filter, RfNew Coroutine(producer)))); }
int main() { InitItemRepository(&gItemRepository); std::thread producer(ProducerTask); std::thread consumer(ConsumerTask); producer.join(); consumer.join(); }