File: packagedtask.cc

package info (click to toggle)
c%2B%2B-annotations 10.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 10,536 kB
  • ctags: 3,247
  • sloc: cpp: 19,157; makefile: 1,521; ansic: 165; sh: 128; perl: 90
file content (64 lines) | stat: -rw-r--r-- 1,522 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <fstream>
#include <future>
#include <mutex>
#include <thread>
#include <condition_variable>

using namespace std;

//code
mutex carDetailsMutex;
condition_variable condition;
string carDetails;
packaged_task<size_t (std::string const &)> serviceTask;

size_t volkswagen(string const &type)
{
    cout << "performing maintenance by the book for a " << type << '\n';
    return type.size() * 75;            // the size of the bill
}

size_t peugeot(string const &type)
{
    cout << "performing quick and dirty maintenance for a " << type << '\n';
    return type.size() * 50;             // the size of the bill
}

void garage()
{
    while (true)
    {
        unique_lock<mutex> lk(carDetailsMutex);
        while (carDetails.empty())
            condition.wait(lk);

        cout << "servicing a " << carDetails << '\n';
        serviceTask(carDetails);
        carDetails.clear();
    }
}

int main()
{
    thread(garage).detach();

    while (true)
    {
        string car;
        if (not getline(cin, car) || car.empty())
            break;
        {
            lock_guard<mutex> lk(carDetailsMutex);
            carDetails = car;
        }
        serviceTask =  packaged_task<size_t (string const &)>(
                    car[0] == 'v' ? volkswagen : peugeot
                );
        auto bill = serviceTask.get_future();
        condition.notify_one();
        cout << "Bill for servicing a " << car <<
                                ": EUR " << bill.get() << '\n';
    }
}
//=