Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // lab1mmyller.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <iostream>
- #include <thread>
- #include <string>
- #include <mutex>
- #include <vector>
- #include <chrono>
- #include <atomic>
- using namespace std;
- using namespace std::chrono;
- std::mutex my_mutex;
- unsigned long long int my_int = 0;
- std::atomic_int atomic_ = 0;
- void thread_function(string i) {
- cout << "Thread function no. "<< i << endl;
- }
- void printing(string text) {
- for (unsigned int i = 0; i < 50; i++) {
- lock_guard<mutex> guard(my_mutex);
- cout << text << endl;
- }
- }
- void incrementing() {
- for (unsigned long long int i = 0; i < 10000000; i++) {
- lock_guard<mutex> guard(my_mutex);
- my_int++;
- }
- cout << my_int << endl;
- }
- void incrementing_atomic() {
- for (unsigned long long int i = 0; i < 10000000; i++) {
- atomic_++;
- }
- cout << atomic_ << endl;
- }
- class FuncObject {
- public :
- void operator()(string i) const {
- thread_function(i);
- }
- };
- class MyClass {
- public:
- void threading(string i) {
- thread_function(i);
- }
- };
- int main()
- {
- FuncObject obj;
- thread my_thread(thread_function, "1");
- my_thread.join();
- thread my_thread3(obj, "3");
- my_thread3.join();
- MyClass my_class;
- thread my_thread4(&MyClass::threading, my_class, "4");
- my_thread4.join();
- thread my_thread5([](string i) {
- cout << "Thread function no. " << i << endl;
- }, "5");
- my_thread5.join();
- auto start = high_resolution_clock::now();
- thread my_thread6(incrementing);
- my_thread6.join();
- auto stop = high_resolution_clock::now();
- auto duration = duration_cast<milliseconds>(stop - start);
- cout << "Single incrementation with mutex: " << duration.count() << endl;
- // 2
- for (int i = 0; i < 20; i++) {
- thread th(printing, "elo");
- th.join();
- }
- // With mutex
- std::vector<thread> my_threads;
- auto start_with_mutex = high_resolution_clock::now();
- for (int i = 0; i < 10; i++) {
- my_threads.emplace_back(incrementing);
- }
- for (int i = 0; i < 10; i++) {
- my_threads[i].join();
- }
- auto end_with_mutex = high_resolution_clock::now();
- cout << "Ten incrementattions with mutex: " << duration_cast<milliseconds>(end_with_mutex - start_with_mutex).count() << endl;
- std::vector<thread> my_threads2;
- // With atomic
- auto start_with_atomic = high_resolution_clock::now();
- for (int i = 0; i < 10; i++) {
- my_threads2.emplace_back(incrementing_atomic);
- }
- for (int i = 0; i < 10; i++) {
- my_threads2[i].join();
- }
- auto end_with_atomic = high_resolution_clock::now();
- cout << "Ten incrementations with atomic: " << duration_cast<milliseconds>(end_with_atomic - start_with_atomic).count() << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement