3 / 3 / 0
Регистрация: 02.04.2017
Сообщений: 273
1

Стек cmd содержит комманды; как сделать так, чтобы эти команды выполнялись в отдельных потоках?

17.11.2017, 09:05. Показов 543. Ответов 6
Метки нет (Все метки)

Стек cmd содержит комманды. Нужно сделать так, чтобы эти команды выполнялись в отдельных потоках. Пробовал 2-мя способами.

C++
1
2
3
4
5
6
7
8
9
10
11
12
Stack<std::thread> ths;
                cmds3=cmds;
    
                while(cmds3.size()>0){
                    ths.Push(std::shared_ptr<std::thread>(new std::thread(*cmds3.front())));
                    cmds3.Pop();
                }
 
                for (auto th : ths)
                    th->join();
 
                break;
Не уверен, что так можно, но решил попробовать. Компилируется, но при выполнении
C++
1
2
3
terminate called after throwing an instance of 'std::system_error'
  what():  Invalid argument
Aborted (core dumped)
и

C++
1
2
3
4
5
6
7
while(cmds3.size()>0){
                    ths.Push(std::shared_ptr<std::thread>(new std::thread(*cmds3.front())));
                    ths->join();                    
                    cmds3.Pop();
                    ths.Pop();
                
                }
Bash
1
2
3
main.cpp:251:9: error: base operand of ‘->’ has non-pointer type ‘Stack<std::thread>’
      ths->join();     
         ^
Что еще можно сделать?
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
17.11.2017, 09:05
Ответы с готовыми решениями:

Можно ли сделать так чтобы скрипты выполнялись несколько раз через определенное время?
Можно ли сделать так чтобы скрипты выполнялись несколько раз через определенное время.

Как сделать так, чтобы программа на free pascal или ее часть выполнялась на всех ядрах и потоках?
Как сделать так, чтобы программа на free pascal или ее часть выполнялась на всех ядрах и потоках?...

как сделать чтоб команды выполнялись для определенного окна?
#include &lt;vcl.h&gt; #pragma hdrstop ...

при работе рекурсивной функции заканчивается стек и программа соответственно; как сделать так, чтобы она писала "стек закончился"?
Сабж g++ 4.5.0

6
7376 / 6295 / 2859
Регистрация: 14.04.2014
Сообщений: 27,281
17.11.2017, 09:25 2
Что этот Stack хранит? При объявлении указателя нет, а добавляешь указатель.
std::thread принимает функцию; у тебя функции, что ли, в cmd3?
0
3 / 3 / 0
Регистрация: 02.04.2017
Сообщений: 273
17.11.2017, 09:50  [ТС] 3
Цитата Сообщение от nmcf Посмотреть сообщение
у тебя функции, что ли, в cmd3?
Да, это копия основного стека cmd, который содержит команды(функции)

Добавлено через 11 минут
Цитата Сообщение от nmcf Посмотреть сообщение
При объявлении указателя нет, а добавляешь указатель.
Забыл убрать. В начале пробовал еще более странно это делать
C++
1
2
3
4
5
6
7
8
9
10
11
12
case 3:
            {
                Stack<std::thread> ths;
 
                for (auto cmd : cmds)
                    ths.push(std::shared_ptr<std::thread>(new std::thread(*cmd)));
 
                for (auto th : ths)
                    th->join();
 
                break;
}
0
7376 / 6295 / 2859
Регистрация: 14.04.2014
Сообщений: 27,281
17.11.2017, 10:24 4
Это компилируется? Почему не используешь стандартный std::stack?
0
3 / 3 / 0
Регистрация: 02.04.2017
Сообщений: 273
17.11.2017, 17:31  [ТС] 5
nmcf, компилируется, и отчасти работает, только зацикливается. Должен был вывести только один print
Кликните здесь для просмотра всего текста

Bash
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
================
Command: print
terminate called after throwing an instance of 'std::system_error'
================
Command: print
  what():  Resource temporarily unavailable
================
Command: print
Command: print
================
Aborted (core dumped)


Цитата Сообщение от nmcf Посмотреть сообщение
Почему не используешь стандартный std::stack?
Стандартные нельзя.

Добавлено через 6 часов 19 минут
Вообще-то я удивлен, что это компилируется. Нашел этот кусок кода в интернете, он был для очереди. Попытался передать под себя. Может быть есть идеи как это делается?
0
7376 / 6295 / 2859
Регистрация: 14.04.2014
Сообщений: 27,281
17.11.2017, 19:09 6
Что конкретно в этом cmd?
0
3 / 3 / 0
Регистрация: 02.04.2017
Сообщений: 273
18.11.2017, 16:25  [ТС] 7
nmcf,
В общем смысл задания реализовать с помощью лямбда-выражений набор команд, совершающих операции над контенйром 1-го уровня

в cmds находятся лямбда-выражения
в cmdsNames имена


219-230 - выполнение выражений из стека, это и пытаюсь сделать

Ps надо было делать это для дерева, но с ним еще более тяжко... Пытался для стека
Кликните здесь для просмотра всего текста

C++
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
typedef std::function<void(void)> Command;
 
int main()
{
    Btree<Figure> b;
    Stack<Command> cmds;
    Stack<std::string> cmdsNames;
 
    
    Stack<Command> cmds3;
    Stack<Command> cmds2;
    Stack<std::string> cmdsNames2;
 
    std::mutex mtx;
 
    Command cmdInsert = [&]()
    {
        std::lock_guard<std::mutex> guard(mtx);
 
        unsigned int seed = std::chrono::system_clock::now().time_since_epoch().count();
 
        std::default_random_engine generator(seed);
        std::uniform_int_distribution<int> distrFigureType(1, 3);
        std::uniform_int_distribution<int> distrFigureParam(1, 10);
 
        std::cout << "================" << std::endl;
        std::cout << "Command: insert" << std::endl;
 
        switch (distrFigureType(generator))
        {
            case 1:
            {
                std::cout << "================" << std::endl;
                std::cout << "Inserted: square" << std::endl;
 
                double side = distrFigureParam(generator);
 
                b.bstInsert(std::shared_ptr<Square>(new Square(side)));
 
                break;
            }
 
            case 2:
            {
                std::cout << "================" << std::endl;
                std::cout << "Inserted: rectangle" << std::endl;
 
                double sideA = distrFigureParam(generator);
                double sideB = distrFigureParam(generator);
 
                b.bstInsert(std::shared_ptr<Rectangle>(new Rectangle(sideA, sideB)));
 
                break;
            }
 
            case 3:
            {
                std::cout << "================" << std::endl;
                std::cout << "Inserted: trapezoid" << std::endl;
 
                double sideA = distrFigureParam(generator);
                double sideB = distrFigureParam(generator);
                double height = distrFigureParam(generator);
 
                b.bstInsert(std::shared_ptr<Trapezoid>(new Trapezoid(sideA, sideB, height)));
 
                break;
            }
        }
    };
 
    Command cmdErase = [&]()
    {
        std::lock_guard<std::mutex> guard(mtx);
 
        const double AREA = 24.0;
 
        std::cout << "================" << std::endl;
        std::cout << "Command: erase" << std::endl;
 
        if (b.size() == 0)
        {
            std::cout << "================" << std::endl;
            std::cout << "Stack is empty" << std::endl;
        }
        else
        {
            std::shared_ptr<Figure> first = b.front();
 
            while (true)
            {
                bool isRemoved = false;
 
                for (auto figure : b)
                {
                    if (figure->area() < AREA)
                    {
                        std::cout << "================" << std::endl;
                        std::cout << "Removed" << std::endl;
                        
                        figure->print();
                        std::cout << "Area: " << figure->area() << std::endl;
 
                        b.bstInsert(b.front());
                        isRemoved = true;
 
                        break;
                    }
                }
 
                if (!isRemoved)
                    break;
        }   }
 
    };
 
 
    Command cmdPrint = [&]()
    {
        std::lock_guard<std::mutex> guard(mtx);
 
        std::cout << "================" << std::endl;
        std::cout << "Command: print" << std::endl;
        
        for (auto figure : b)
        {
            figure->print();
 
            std::cout << "Area: " << figure->area() << std::endl;
        }
    };
    
    while (true)
    {
        unsigned int action;
 
        std::cout << "================" << std::endl;
        std::cout << "Menu:" << std::endl;
        std::cout << "1) Add command" << std::endl;
        std::cout << "2) Erase command" << std::endl;
        std::cout << "3) Execute commands" << std::endl;
        std::cout << "4) Print commands" << std::endl;
        std::cout << "0) Quit" << std::endl;
        std::cin >> action;
 
        if (action == 0)
            break;
        
        if (action > 4)
        {
            std::cout << "Error: invalid action" << std::endl;
 
            continue;
        }
 
        switch (action)
        {
            case 1:
            {
                unsigned int commandType;
 
                std::cout << "================" << std::endl;
                std::cout << "1) Insert" << std::endl;
                std::cout << "2) Erase" << std::endl;
                std::cout << "3) Print" << std::endl;
                std::cout << "0) Quit" << std::endl;
                std::cin >> commandType;
 
                if (commandType > 0)
                {
                    if (commandType > 3)
                    {
                        std::cout << "Error: invalid command type" << std::endl;
 
                        continue;
                    }
 
                    switch (commandType)
                    {
                        case 1:
                        {
                            cmds.Push(std::shared_ptr<Command>(&cmdInsert, [](Command*){}));
                            cmdsNames.Push(std::shared_ptr<std::string>(new std::string("Insert")));
 
                            break;
                        }
                        
                        case 2:
                        {
                            cmds.Push(std::shared_ptr<Command>(&cmdErase, [](Command*){}));
                            cmdsNames.Push(std::shared_ptr<std::string>(new std::string("Erase")));
 
                            break;
                        }
 
                        case 3:
                        {
                            cmds.Push(std::shared_ptr<Command>(&cmdPrint, [](Command*){}));
                            cmdsNames.Push(std::shared_ptr<std::string>(new std::string("Print"))); 
 
                            break;
                        }
                    }
                }
 
                break;
            }
 
            case 2:
            {
        
                std::cout << "================" << std::endl;
                std::cout << "Front command erased" << std::endl;
                cmds.Pop();
                cmdsNames.Pop();
                break;
            }
 
            case 3:
                    {
                    Stack<std::thread> ths;
 
                    for (auto cmd : cmds)
                        ths.Push(std::shared_ptr<std::thread>(new std::thread(*cmd)));
 
                    for (auto th : ths)
                        th->join();
 
                    break;
            }
    
            case 4:
            {
                std::cout << "================" << std::endl;
 
                if (cmds.size() == 0)
                    {std::cout << "Commands list is empty" << std::endl;}
                else {
                        cmdsNames2=cmdsNames;
                    while (cmdsNames2.size()>0) {
                        printf("=========\n");
                            std::cout << *cmdsNames2.front() << std::endl;
                            cmdsNames2.Pop();
                    }                       
                }
                break;
            }
        }
    }
    
    return 0;
}


Добавлено через 20 часов 14 минут
К сожалению, ничего выше не заработало

Добавлено через 9 минут
Но, есть работающий пример для очереди.
C++
1
2
3
4
5
6
7
8
9
10
11
12
case 3:
            {
                Queue<std::thread> ths;
 
                for (auto cmd : cmds)
                    ths.push(std::shared_ptr<std::thread>(new std::thread(*cmd)));
 
                for (auto th : ths)
                    th->join();
 
                break;
}
Добавлено через 21 минуту
Еще пробовал так.
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
case 3:
                    {
                    Btree<std::thread> ths;
            Btree<std::thread> th;
                cmds2=cmds;
                th = ths;
            while(cmds2.size()>0){
                ths.Insert(std::shared_ptr<std::thread>(new std::thread(cmds2)));
            }
            th=ths;
            while(ths.size()>0){
            ths.front()->join();
            ths.Insert(ths.front());
            }
но
Bash
1
2
3
4
5
6
7
8
9
10
11
In file included from main.cpp:1:0:
/usr/include/c++/4.8/functional: In instantiation of ‘struct std::_Bind_simple<Stack<std::function<void()> >()>’:
/usr/include/c++/4.8/thread:137:47:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = Stack<std::function<void()> >&; _Args = {}]’
main.cpp:251:66:   required from here
/usr/include/c++/4.8/functional:1697:61: error: no type named ‘typein ‘class std::result_of<Stack<std::function<void()> >()>’
       typedef typename result_of<_Callable(_Args...)>::type result_type;
                                                             ^
/usr/include/c++/4.8/functional:1727:9: error: no type named ‘typein ‘class std::result_of<Stack<std::function<void()> >()>’
         _M_invoke(_Index_tuple<_Indices...>)
         ^
make: *** [all] Error 1
Не понимаю в чем проблема
0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
18.11.2017, 16:25
Помогаю со студенческими работами здесь

Как сделать, чтобы методы выполнялись последовательно
Добрый день! У меня есть контролер, в нём 2 метода: добавление графики и загрузка данных с сервера....

Как сделать, чтобы потоки выполнялись параллельно?
у меня есть 6 потоков, но как мне сделать чтобы они шли параллельно ? static void Main(string...

Как сделать так, чтобы при выполнении команды PING в файл записывалась только статистика?
Как сделать так, что бы выполнении команды: ping ya.ru -n 10 в файл записывалось только статистика?...

Как вызвать переопределить метод из дочернего класса так, чтобы выполнялись еще функции в родительском
У меня структура такова: Интерфейс IKey (Содержит void Open) public interface IKey { public...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru