repl.it
@SharkFin/

Multithread Testing

C++11

No description

fork
loading
Files
  • main.cpp
main.cpp
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
#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
#include <future>

std::mutex mu;

void func1(int x) {
	for(int i=0;i<x;i++) {
		//mu.lock();
		std::cout << "1" << std::flush;
		//mu.unlock();
		std::this_thread::sleep_for(std::chrono::milliseconds(30));
	}
}

void func2(int x) {
	for(int i=0;i<x;i++) {
		//mu.lock();
		std::cout << "2" << std::flush;
		//mu.unlock();
		std::this_thread::sleep_for(std::chrono::milliseconds(30));
	}
}

int func3(int one, int two) {
	return one * two;
}

int main() {
  std::cout << "Main, func1, func2 working independantly" << std::endl;

	int loops = 10;
	std::thread first(func1, loops);
	std::thread second(func2, loops);
	auto future =  std::async(func3, 45, 61);
	int product = future.get();

	std::cout << "Product is: " << product << std::endl;

	std::cout << "Joining first" << std::endl;
	first.join();

	std::cout << "Joining second" << std::endl;
	// When this is uncommented out, it breaks for some reason. If second.join is not commented.
	// It doesn't get to the above cout (Joining second) somehow. Okay, that makes perfect sense. (doesn't)
	// Also sometimes it does, if it's looping long enough, and if the delays are close eno
	second.join();

	std::cout << std::endl << "Complete" << std::endl;
	return 0;
}
?