zoukankan      html  css  js  c++  java
  • C/C++ Threads): Creating worker threads that will be listening to jobs and executing them concurrently when wanted

    Suppose we have two workers. Each worker has an id of 0 and 1. Also suppose that we have jobs arriving all the time, each job has also an identifier 0 or 1 which specifies which worker will have to do this job.

    I would like to create 2 threads that are initially locked, and then when two jobs arrive, unlock them, each of them does their job and then lock them again until other jobs arrive.

    I have the following code:

      #include <iostream>
      #include <thread>
      #include <mutex>
    
      using namespace std;
    
      struct job{
    
          thread jobThread;
          mutex jobMutex;
    
      };
    
      job jobs[2];
    
    
      void executeJob(int worker){
    
          while(true){
    
              jobs[worker].jobMutex.lock();
    
              //do some job
    
          }
    
       }
    
      void initialize(){
    
          int i;
          for(i=0;i<2;i++){
                    jobs[i].jobThread = thread(executeJob, i);
          }
    
       }
    
      int main(void){
    
          //initialization
          initialize();
    
          int buffer[2];
          int bufferSize = 0;
    
          while(true){
              //jobs arrive here constantly, 
                //once the buffer becomes full, 
                //we unlock the threads(workers) and they start working
              bufferSize = 2;
              if(bufferSize == 2){
                  for(int i = 0; i<2; i++){
                      jobs[i].jobMutex.unlock();
                  }
              }
               break;
         }
    
      }

    I started using std::thread a few days ago and I'm not sure why but Visual Studio gives me an error saying abort() has been called. I believe there's something missing however due to my ignorance I can't figure out what.

    I would expect this piece of code to actually

    1. Initialize the two threads and then lock them

    2. Inside the main function unlock the two threads, the two threads will do their job(in this case nothing) and then they will become locked again.

    But it gives me an error instead. What am I doing wrong?

    Thank you in advance!

  • 相关阅读:
    FAN_int2ExcelColChar functions
    How to enables AX email functionality without Outlook
    Global::validateEmail
    Global::time2StrHHMM_DNT
    Global::pickSpecificTable_DNT
    Global::pickSpecificClass_DNT
    Global::pickClassMethod_DNT
    Optimize date2str function
    How to achieve dialog with lookup control
    Optimize str2date function
  • 原文地址:https://www.cnblogs.com/oxspirt/p/7759990.html
Copyright © 2011-2022 走看看