works:programmer:cpp:thread-sync
Синхронизация потоков через scoped_lock
// Example program #include <iostream> #include <string> #include <thread> #include <vector> #include <iostream> #include <stdarg.h> #include <mutex> using namespace std; std::string format(const char *fmt, ...); void start(const int f, const int t, vector<int>* vec); std::mutex vecmgr; int main() { vector<int> vec; start(20, 40, &vec); start(100, 120, &vec); start(200, 240, &vec); string name; cout << "What is your name? "; getline(cin, name); cout << "Hello, " << name << "!\n"; for (auto s: vec) { cout << s << ", "; } cout << endl; } void start(int f, int t, vector<int>* vec) { auto thfunc = [&f, &t, vec] () { // scoped_lock lock{vecmgr}; if (f > t) return; for (int i=f; i<=t; i++) { vec->push_back( i ); } }; thread th(thfunc); th.join(); // th.detach(); }
works/programmer/cpp/thread-sync.txt · Последнее изменение: 2020/01/23 14:40 — 127.0.0.1