fbpx

C++: Concurrent Computing

Bjarne-stroustrup
 

Using either native language concurrency syntax or freely available libraries write a program to display the strings “Enjoy” “Rosetta” “Code”, one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.

#include <thread>
#include <iostream>
#include <vector>
#include <random>
#include <chrono> 

int main()
{
	std::random_device rd;
	std::mt19937 eng(rd()); // mt19937 generator with a hardware random seed.
	std::uniform_int_distribution<> dist(1,1000);
	std::vector<std::thread> threads;

	for(const auto& str: {"Enjoy\n", "Rosetta\n", "Code\n"}) {
		// between 1 and 1000ms per our distribution
		std::chrono::milliseconds duration(dist(eng)); 

		threads.emplace_back([str, duration](){                                                                    
			std::this_thread::sleep_for(duration);
			std::cout << str;
		});
	}

	for(auto& t: threads) t.join(); 

	return 0;
}

Output:

Enjoy
Code
Rosetta

#include <iostream>
#include <ppl.h> // MSVC++

void a(void) { std::cout << "Eat\n";   }
void b(void) { std::cout << "At\n";    }
void c(void) { std::cout << "Joe's\n"; }

int main()
{
	// function pointers
	Concurrency::parallel_invoke(&a, &b, &c);

	// C++11 lambda functions
	Concurrency::parallel_invoke(
	[]{ std::cout << "Enjoy\n";   },
	[]{ std::cout << "Rosetta\n"; },
	[]{ std::cout << "Code\n";    }
	);
	return 0;
}

Output:

Joe's
Eat
At
Enjoy
Code
Rosetta

SOURCE

Content is available under GNU Free Documentation License 1.2.