Untitled
unknown
c_cpp
3 years ago
1.1 kB
6
Indexable
#include <iostream> #include <thread> #include <vector> #include <mutex> #include <ctime> using namespace std; mutex mtx; // adding random numbers to vector void addNumber(vector<int> &data) { srand(time(NULL)); if (mtx.try_lock()) { if (data.size() > 1) { data.push_back(rand()); } mtx.unlock(); } for (int i = 0; i < data.size(); i++) cout << data[i] << " "; cout << "\n"; }; // removing numbers from the vector tail void removeNumber(vector<int> &data) { if (mtx.try_lock()) { if (data.size() > 1) { data.pop_back(); } mtx.unlock(); } for (int i = 0; i < data.size(); i++) cout << data[i] << " "; cout << "\n"; }; int main() { vector<int> array; for (int i = 0; i < 10; i++) { array.push_back(rand()); } // creating threads thread t1(addNumber, ref(array)); thread t2(removeNumber, ref(array)); t1.join(); t2.join(); cout << "\n" << "Exiting main...";
Editor is loading...