In: Computer Science
C++ application:
Create a C++ application that will exhibit concurrency concepts. Your application should create two threads that will act as counters. One thread should count up to 20. Once thread one reaches 20, then a second thread should be used to count down to 0.
For your created code, provide a written analysis of appropriate concepts that could impact your application.
Please Specifically, Address: Performance Issues with Concurrency Vulnerabilities Exhibited with use of Strings and Security of the Data Types used.
#include
#include
int count = 0; //Initialize a global counter
void count_up() {
std::cout << "count up started" << std::endl;
while(count < 20){
count++; //count up
std::cout << count << std::endl; //print result
}}
void count_down() {
std::cout << "count down started" << std::endl;
while(count >= 0){
std::cout << count << std::endl; //print result
count--; //count down
}}
int main() {
//Start a thread
std::thread t1(count_up);
t1.join(); //Join the thread with main thread/program otherwise
second thread will start executing
std::thread t2(count_down); //Start second thread
t2.join(); //Join the thread with the main thread/program
return 0;
}
Analysis:
''.join() function is used to join the flow of the thread to the main program. If it is not used then both the threads will start executing at the same time. This is the concurrency exhibited in the application.
Security of the data (global variable, count) is not vulnerable since ''.join() function. In the absence of ''.join() function security of global variable can be vulnerable as both the threads will try to access the data at the same time and it might lead to unexpected results.