C + + Threads): Creating worker Threads that'll be listening to jobs and executing them concurrently when wanted

Source: Internet
Author: User
Tags mutex

Suppose we have both workers. Each worker has a ID of 0 and 1 . Also Suppose that we had jobs arriving all the time and each job had Also an identifier 0 or 1 which specifies which The worker would have the to does this job.

I would like-to-create 2 threads that is initially locked, and then when II 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 NamespaceStd; structJob{Thread Jobthread;Mutex Jobmutex; };Job Jobs[2]; voidExecutejob(IntWorker){ While(True){Jobs[Worker].Jobmutex.Lock(); Do some job } } voidInitialize(){ IntI; For(I=0;I<2;I++){Jobs[I].Jobthread=Thread(Executejob,I); } } IntMain(void){ InitializationInitialize(); IntBuffer[2]; IntBufferSize= 0; While(True){ Jobs arrive here constantly, Once the buffer becomes full, We unlock the threads (workers) and they start workingBufferSize= 2; If(BufferSize== 2) { for  (int I = 0; I<2  I++) { Jobs[i jobmutex.} } break } }       /span>                 

I started using std::thread a few days ago and I am not sure so 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 threads and then lock them

    2. Inside the main function unlock the "the" and "the" threads, the "the" and "the" "Do" their job (in the "this") and then they wil L become locked again.

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

Thank you in advance!

C + + Threads): Creating worker Threads that'll be listening to jobs and executing them concurrently when wanted

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.