首页 > 编程语言 > 详细

C/C++ Threads): Creating worker threads that will be listening to jobs and executing them concurrently when wanted

时间:2017-10-31 10:15:51      阅读:247      评论:0      收藏:0      [点我收藏+]

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!

C/C++ Threads): Creating worker threads that will be listening to jobs and executing them concurrently when wanted

原文:http://www.cnblogs.com/oxspirt/p/7759990.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!