Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdafx.h"
- #include <iostream>
- #include <thread>
- #include <mutex>
- #include <string>
- #include <chrono>
- #include <vector>
- #include <algorithm>
- #include <atomic>
- using namespace std;
- /////////////////////////////////////////////1
- void foo(int Z)
- {
- for (int i = 0; i < Z; i++) {
- cout << "Thread - global function\n";
- }
- }
- class bar {
- public:
- void operator()(int x)
- {
- for (int i = 0; i < x; i++)
- cout << "Thread - function object\n";
- }
- void foo(int ii) {
- for (int y = 0; y < ii;y++) {
- cout << "Thread - class method\n";
- }
- }
- };
- ////////////////////////////////////////////1
- ////////////////////////////////////////////2
- mutex mu;
- static const int threads_number = 20;
- void printText(string text) {
- for (int i = 0; i < 50; i++) {
- cout << i << " " << text << endl;
- }
- }
- void func(string msg)
- {
- mu.lock();
- printText(msg);
- mu.unlock();
- }
- ////////////////////////////////////////////2
- ////////////////////////////////////////////3
- int globalIntegerVariable = 0;
- void increment() {
- for (int i = 0;i < 10000000;i++) {
- globalIntegerVariable++;
- }
- }
- void funcA() {
- }
- void funcB() {
- }
- ////////////////////////////////////////////3
- int main()
- {
- /*
- Task 1
- */
- thread th1(foo, 50);
- thread th2(bar(), 50);
- auto f = [](int x) {
- for (int i = 0; i < x; i++)
- cout << "Thread - lambda expression\n";
- };
- thread th3(f, 50);
- thread th4(&bar::foo, bar(), 50);
- th1.join();
- th2.join();
- th3.join();
- th4.join();
- /*
- Task 2
- */
- thread th[threads_number];
- for (int i = 0; i < threads_number; i++) {
- th[i] = thread(&func, "Text to print");
- }
- for (int i = 0; i < threads_number; ++i) {
- th[i].join();
- }
- /*
- Task 3
- */
- using clock = std::chrono::steady_clock;
- vector<thread> workers;
- for (int i = 0; i < 10; i++) {
- workers.push_back(thread([]()
- {
- cout << "thread function\n";
- }));
- }
- clock::time_point start = clock::now();
- clock::time_point end = clock::now();
- clock::duration execution_time = end - start;
- cout << endl<< execution_time.count()<<endl;
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement