int main() { typedef std::queue<char> Queue; LockObject<Queue> shared_queue; std::atomic<bool> quit; // producer adds items to the queue std::thread producer([&shared_queue, &quit]() { while (!quit) { Locker<Queue> lock = shared_queue.lock(); // locks the mutex Queue & queue = lock.get(); for (char c = ' '; c <= '~'; ++c) { queue.push(c); } } }); // consumer thread removes items from the queue std::thread consumer([&shared_queue, &quit]() { while (!quit) { std::string current; { Locker<Queue> lock = shared_queue.lock(); // locks the mutex Queue & queue = lock.get(); if (queue.empty()) return; while (!queue.empty()) { current.push_back(std::move(queue.front())); queue.pop(); } } std::cout << current << '\n'; current.clear(); } }); std::this_thread::sleep_for(std::chrono::milliseconds(1)); quit = true; producer.join(); consumer.join(); }
int main() { srand(13); printf("This is lab 8\n"); s = sem_apply(1); n = sem_apply(0); e = sem_apply(BUFFER_SIZE); buffer = 0; int pid = fork(); if (pid == 0) producer(); else consumer(); }
int main() { // request RequestString request_; // consumer std::thread first_consumer_{ consumer(request_) }; std::thread second_consumer_{ consumer(request_) }; // producer std::thread producer_{ producer(request_) }; // join producer_.join(); first_consumer_.join(); second_consumer_.join(); }
static jlong nativeCreateFromSurfaceTexture(JNIEnv* env, jclass clazz, jobject surfaceTextureObj) { sp<IGraphicBufferProducer> producer(SurfaceTexture_getProducer(env, surfaceTextureObj)); if (producer == NULL) { jniThrowException(env, "java/lang/IllegalArgumentException", "SurfaceTexture has already been released"); return 0; } sp<Surface> surface(new Surface(producer, true)); if (surface == NULL) { jniThrowException(env, OutOfResourcesException, NULL); return 0; } surface->incStrong(&sRefBaseOwner); return jlong(surface.get()); }
static PT_THREAD(driver_thread(struct pt *pt)) { static struct pt pt_producer, pt_consumer; PT_BEGIN(pt); PT_SEM_INIT(&empty, 0); PT_SEM_INIT(&full, BUFSIZE); PT_INIT(&pt_producer); PT_INIT(&pt_consumer); PT_WAIT_THREAD(pt, producer(&pt_producer) & consumer(&pt_consumer)); PT_END(pt); }
int main() { vec.reserve(BUFFER_SIZE*2); std::thread producer(produce), consumer(consume); producer.join(); // Produce some more producer = std::thread(produce); auto another_producer = std::thread(produce); producer.join(); another_producer.join(); // Tell consumer we are done producing { std::lock_guard<std::mutex> lock(mu); done = true; } empty.notify_one(); consumer.join(); }
int main(int argc, char** argv) { int i; long long sum, *arr; __cilkrts_stack_queue* q; printf("Usage: %s numelements numthreads\n", argv[0]); if (argc > 3) { abort(); } if (argc > 2) numelems = atoi(argv[1]); if (argc == 3) numthreads = atoi(argv[2]); // ---------------------------------------- arr = (long long*)malloc(sizeof(long long) * (numthreads/2)); q = make_stack_queue(); printf("Q created and initialized: %p\n",q); printf("Starting %d producers and consumers, each will pass %d elements.\n", numthreads/2, numelems); for (i=0; i<numthreads/2; i++) cilk_spawn producer(q); for (i=0; i<numthreads/2; i++) arr[i] = cilk_spawn consumer(q); cilk_sync; printf("All producers and consumers finished.\n"); sum = 0; for (i=0; i<numthreads/2; i++) sum += arr[i]; printf("Total: %ld\n", sum); // Default parameters should result in: 1999998000000 if ( numelems == 1000000 && numthreads == 8 && sum != 1999998000000) { printf("ERROR: ANSWER NOT CORRECT, EXPECTING %ld\n", 1999998000000); fflush(stdout); abort(); } }
RemoveTrackCommand::RemoveTrackCommand(MultitrackModel& model, int trackIndex, QUndoCommand* parent) : QUndoCommand(parent) , m_model(model) , m_trackIndex(trackIndex) , m_trackType(model.trackList().at(trackIndex).type) { if (m_trackType == AudioTrackType) setText(QObject::tr("Remove audio track")); else if (m_trackType == VideoTrackType) setText(QObject::tr("Remove video track")); // Save track XML. int mlt_index = m_model.trackList().at(m_trackIndex).mlt_index; QScopedPointer<Mlt::Producer> producer(m_model.tractor()->multitrack()->track(mlt_index)); if (producer && producer->is_valid()) { m_xml = MLT.XML(producer.data()); m_trackName = QString::fromUtf8(producer->get(kTrackNameProperty)); } }
void main (int argc, char *argv[]) { circular_buffer *mc; // Used to access buffers in shared memory page uint32 h_mem; // Handle to the shared memory page sem_t s_procs_completed_pc; // Semaphore to signal the original producer_consumer process that we're done int id; //producer_consumer id lock_t lock; //lock id int type; //process type if (argc != 6) { Printf("Usage: "); Printf(argv[0]); Printf(" <handle_to_shared_memory_page> <handle_to_page_mapped_semaphore><process id> <process type>\n"); Exit(); } // Convert the command-line strings into integers for use as handles h_mem = dstrtol(argv[1], NULL, 10); // The "10" means base 10 s_procs_completed_pc = dstrtol(argv[2], NULL, 10); id = dstrtol(argv[3],NULL,10); lock= dstrtol(argv[4],NULL,10); type= dstrtol(argv[5],NULL,10); // Printf("type is %d\n",type); // Map shared memory page into this process's memory space if ((mc = (circular_buffer *)shmat(h_mem)) == NULL) { Printf("Could not map the virtual address to the memory in "); Printf(argv[0]); Printf(", exiting...\n"); Exit(); } //decide which process to run flag=0; if (type== PRODUCER){ producer(mc,id,lock); }else if(type == CONSUMER){ consumer(mc,id,lock); }else{ Printf("Wrong process\n"); } // Signal the semaphore to tell the original process that we're done Printf("Process_%d_type_%d is complete.\n", id,type); if(sem_signal(s_procs_completed_pc) != SYNC_SUCCESS) { Printf("Bad semaphore s_procs_completed (%d) in ", s_procs_completed_pc); Printf(argv[0]); Printf(", exiting...\n"); Exit(); } }
void TestConcurrentLockingQueue::testConcurrentLockingQueueExhibitsCorrectBehaviour(void) { const size_t length = 10000; std::vector<size_t> resVec; ConcurrentLockingQueue<size_t> queue; std::thread producer(produce, &queue, length); std::thread consumer(consume, &resVec, &queue, length); producer.join(); consumer.join(); //check size CPPUNIT_ASSERT(length == resVec.size()); // check if all values where added in correct order! for (size_t i = 0; i < length; i++) { CPPUNIT_ASSERT(i == resVec[i]); } }
int main() { struct C c; c.x = 1; for (int i = 0; i < 5; ++i) { c.y[i] = -1; } producer(&c); consumer(&c); #pragma omp taskwait for (int i = 0; i < 5; ++i) { c.y[i] = 4; } }
int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); QStringList arguments = app.arguments(); if (app.arguments().count() != 2) { qWarning("Please call the helper with the function to call as argument"); return EXIT_FAILURE; } QString function = arguments.at(1); if (function == QLatin1String("readonly_segfault")) return readonly_segfault(); else if (function == QLatin1String("producer")) return producer(); else if (function == QLatin1String("consumer")) return consumer(); else qWarning() << "Unknown function" << arguments.at(1); return EXIT_SUCCESS; }
int main() { std::vector<std::thread> consumers; std::thread producer(producer_function); for (int i = 0; i < numberOfConsumers; ++i) { consumers.emplace_back(consumer_function, i); } if (producer.joinable()) { producer.join(); } for (int i = 0; i < numberOfConsumers; i++) { if (consumers[i].joinable()) { consumers[i].join(); } } return 0; }
int main() { int pd[2]; if(pipe(pd)==-1) { perror("pipe()"); exit(1); } switch(fork()) { case -1: perror("fork()"); exit(1); break; case 0: /* Syn (cte z roury) */ close(0); /* close(), dup() lze ekvivalentne psát dup2(pd[0],0) */ if(dup(pd[0])==-1) { perror("dup()"); exit(1); } close(pd[0]); close(pd[1]); /* Konzument musí zavrít zápisový konec roury, protoze dokud má nejaký proces rouru otevrenou pro zápis, nenastane na ní EOF a konzument by cekal vecne i po skoncení producenta!!! */ consumer(); break; default: /* Otec (zapisuje do roury) */ if(dup2(pd[1],1)==-1) { /* ekvivalentní close(1);dup(pd[1]) */ perror("dup2()"); exit(1); } close(pd[0]); close(pd[1]); producer(); /* Tady by mohl být wait(), kterým by otec pockal, nez syn dokoncí zpracování. Toto resení ale nelze pouzít, kdyz otec místo volání funkce producer() provede exec(). */ break; } exit(0); }
int main() { // 创建仓库 auto repository = std::make_shared<Repository>(10); // 创建生产者和消费者 Producer producer(repository); Consumer consumer(repository); // 分别设定单位工作的耗时 producer.set_unit_cost(20); consumer.set_unit_cost(30); auto count = 50; // 准备生产和消费的产品数量 std::thread producer_thread([&producer, count] {producer.produce(count); }); std::thread consumer_thread([&consumer, count] {consumer.consume(count); }); // 等待线程合并 producer_thread.join(); consumer_thread.join(); return 0; }
void TestConcurrentLockingQueue::testConcurrentLockingQueueExhibitsCorrectBehaviourInMultiConsumerSetting(void) { // careful the result of length/consumerThreadCount needs to be divisible to a whole integer! const size_t length = 10000; const size_t consumerThreadCount = 4; ConcurrentLockingQueue<size_t> queue; std::vector<std::vector<size_t>> resVecVec; std::vector<size_t> resVec; resVecVec.resize(consumerThreadCount); std::thread producer(produce, &queue, length); std::vector<std::thread> consumerPool; for (size_t i = 0; i < consumerThreadCount; i++) { consumerPool.push_back(std::thread(consume, &resVecVec[i], &queue, length / consumerThreadCount)); } producer.join(); for (size_t i = 0; i < consumerPool.size(); i++) { consumerPool[i].join(); } // flatten vectors auto startIter = resVecVec.begin(); auto endIter = resVecVec.end(); while (startIter != endIter) { std::back_inserter(resVec) = std::copy(startIter->begin(), startIter->end(), std::back_inserter(resVec)); ++startIter; } std::sort(resVec.begin(), resVec.end()); // check if all values are in vector now for (size_t i = 0; i < length; i++) { CPPUNIT_ASSERT(i == resVec[i]); } }
/* Here we can finally define the main function to put everything together */ int main(int argc, char* argv[]) { int num_producer, num_consumer ; int i ; if(argc != 3) { printf("Usage: %s <# producer> <# consumer>\n", argv[0]) ; return 1 ; } num_producer = atoi(argv[1]) ; num_consumer = atoi(argv[2]) ; /* we need to initialize the global queue buffer */ init_queue(&fifo_buffer) ; /* you need to replace the following function calls with actual thread launching */ /* we create num_consumer consumers first */ printf("Creating %d consumers\n", num_consumer) ; for(i=0;i<num_consumer;++i) { consumer( (void*)i); } printf("Creating %d producers\n", num_producer) ; /* we create num_producer producers then */ for(i=0;i<num_producer;++i) { producer( (void*)i); } /* since consumers never quit, we'll notify the user to */ /* end the program by press "Ctrl-C" */ printf("********************************************************\n") ; printf("* All Producers finished, please terminate the program *\n") ; printf("* by \"Ctrl-C\" when all consumers print their items *\n") ; printf("********************************************************\n") ; return 0 ; }
void rpc_pipe(int cpu1, int cpu2) { int pid; set_curr_affinity(cpu1); pid = fork(); if (pid > 0) { producer(); } else { set_curr_affinity(cpu2); consumer(); } if (pid > 0) { int child_status; while (wait(&child_status) > 0) ; } else { /* printf("Child %d back in cos_loader.\n", getpid()); */ exit(getpid()); } }
int main(void) { 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); sleep(10); mq_unlink(qname); /* 删除队列 */ return 0; }
void DataPointsModifier::modify(int poisonPill) { // Start retriving and modifying values bool finished = false; DataPointsConsumer consumer(oldDataStrings); DataPointsProducer producer(newDataStrings); while (!finished) { std::vector<int> data = consumer.consume_to_vector(100000, poisonPill); if (data.back() == poisonPill) { finished = true; } for (auto it = data.begin(); it != data.end(); ++it) { if (*it != poisonPill) *it += 10; } producer.push(data); } }
void BufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer, sp<IGraphicBufferConsumer>* outConsumer, const sp<IGraphicBufferAlloc>& allocator) { LOG_ALWAYS_FATAL_IF(outProducer == NULL, "BufferQueue: outProducer must not be NULL"); LOG_ALWAYS_FATAL_IF(outConsumer == NULL, "BufferQueue: outConsumer must not be NULL"); sp<BufferQueueCore> core(new BufferQueueCore(allocator)); LOG_ALWAYS_FATAL_IF(core == NULL, "BufferQueue: failed to create BufferQueueCore"); sp<IGraphicBufferProducer> producer(new BufferQueueProducer(core)); LOG_ALWAYS_FATAL_IF(producer == NULL, "BufferQueue: failed to create BufferQueueProducer"); sp<IGraphicBufferConsumer> consumer(new BufferQueueConsumer(core)); LOG_ALWAYS_FATAL_IF(consumer == NULL, "BufferQueue: failed to create BufferQueueConsumer"); *outProducer = producer; *outConsumer = consumer; }
void WINAPI producer(int id) { WaitForSingleObject(full,INFINITE); Sleep(Rand()*producer_wait_time); WaitForSingleObject(Mutex,INFINITE); Goods[store].id=product_id; Goods[store].producer_id=id; store++; product_id++; handle_count++; ftime(&tp); ptr=localtime(&(tp.time)); printf("操作次数:%d ",handle_count); printf("生产者%d生产编号%d的产品,仓库产品数:%d\n\n",id,Goods[store-1].id,store); ReleaseMutex(Mutex); ReleaseSemaphore(empty,1,NULL); Sleep(500); product_id=1; tmp++; if(tmp < sum_count*2) producer(id); }
int main(int argc, char *argv[]) { int ch, n = 10; acl::acl_cpp_init(); acl::log::stdout_open(true); while ((ch = getopt(argc, argv, "hn:")) > 0) { switch (ch) { case 'h': usage(argv[0]); return 0; case 'n': n = atoi(optarg); break; default: break; } } acl::channel<int> chan1; acl::channel<A> chan2; acl::channel<acl::string*> chan3; fiber_consumer consumer(n, chan1, chan2, chan3); consumer.start(); fiber_producer producer(n, chan1, chan2, chan3); producer.start(); acl::fiber::schedule(); return 0; }
sp<ANativeWindow> android_SurfaceTexture_getNativeWindow(JNIEnv* env, jobject thiz) { sp<GLConsumer> surfaceTexture(SurfaceTexture_getSurfaceTexture(env, thiz)); sp<IGraphicBufferProducer> producer(SurfaceTexture_getProducer(env, thiz)); sp<Surface> surfaceTextureClient(surfaceTexture != NULL ? new Surface(producer) : NULL); return surfaceTextureClient; }
void OverwriteCommand::undo() { Mlt::Producer producer(MLT.profile(), "xml-string", m_playlistXml.toUtf8().constData()); Mlt::Playlist playlist(producer); m_model.overwriteFromPlaylist(playlist, m_trackIndex, m_position); }
void AppendCommand::redo() { Mlt::Producer producer(MLT.profile(), "xml-string", m_xml.toUtf8().constData()); m_clipIndex = m_model.appendClip(m_trackIndex, producer); }
//生产线程入口函数 void *producer_thread_fun(void *arg) { int realarg = (int)arg;//强制类型转换参数 producer(realarg); return NULL; }
int run_main (int argc, ACE_TCHAR *argv[]) { int retval = 0; MCT_Config config; retval = config.open (argc, argv); if (retval != 0) return 1; const ACE_TCHAR *temp = ACE_TEXT ("Multicast_Test"); ACE_TString test = temp; u_long role = config.role (); if (ACE_BIT_DISABLED (role, MCT_Config::PRODUCER) || ACE_BIT_DISABLED (role, MCT_Config::CONSUMER)) { if (ACE_BIT_ENABLED (role, MCT_Config::PRODUCER)) test += ACE_TEXT ("-PRODUCER"); else test += ACE_TEXT ("-CONSUMER"); } // Start test only if options are valid. ACE_START_TEST (test.c_str ()); // Register a signal handler to close down application gracefully. ACE_Sig_Action sa ((ACE_SignalHandler) handler, SIGINT); // Dump the configuration info to the log if caller passed debug option. if (config.debug ()) config.dump (); ACE_Reactor *reactor = ACE_Reactor::instance (); MCT_Task *task = new MCT_Task (config, reactor); if (ACE_BIT_ENABLED (role, MCT_Config::CONSUMER)) { ACE_DEBUG ((LM_INFO, ACE_TEXT ("Starting consumer...\n"))); // Open makes it an active object. retval += task->open (); } // now produce the datagrams... if (ACE_BIT_ENABLED (role, MCT_Config::PRODUCER)) retval += producer (config); if (ACE_BIT_ENABLED (role, MCT_Config::CONSUMER)) { // and wait for everything to finish ACE_DEBUG ((LM_INFO, ACE_TEXT ("start waiting for consumer to finish...\n"))); // Wait for the threads to exit. // But, wait for a limited time since we could hang if the last udp // message isn't received. ACE_Time_Value max_wait ( config.wait ()/* seconds */); ACE_Time_Value wait_time (ACE_OS::gettimeofday () + max_wait); ACE_Time_Value *ptime = ACE_BIT_ENABLED (role, MCT_Config::PRODUCER) ? &wait_time : 0; if (ACE_Thread_Manager::instance ()->wait (ptime) == -1) { // We will no longer wait for this thread, so we must // force it to exit otherwise the thread will be referencing // deleted memory. finished = 1; reactor->end_reactor_event_loop (); if (errno == ETIME) ACE_ERROR ((LM_ERROR, ACE_TEXT ("maximum wait time of %d msec exceeded\n"), max_wait.msec ())); else ACE_OS::perror (ACE_TEXT ("wait")); ++error; // This should exit now that we ended the reactor loop. task->wait (); } } delete task; ACE_END_TEST; return (retval == 0 && error == 0) ? 0 : 1; }
void UpdateCommand::undo() { Mlt::Producer producer(MLT.profile(), "xml-string", m_oldXml.toUtf8().constData()); m_model.update(m_row, producer); }
void InsertCommand::redo() { Mlt::Producer producer(MLT.profile(), "xml-string", m_xml.toUtf8().constData()); m_model.insert(producer, m_row); }