neat little program has global variables, what is alternative

I wrote this neat little program that has global variables in it. I have been told never to use global variables. Or atleast that any time you do there is a better way that you could have and should have done it instead. I cant think of any way to reproduce this same functionality without using global variables. So I was wondering if one of you smart fellows would know how I might have have written this application differently inorder to avoid global variables.

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
#include <iostream>
#include <string>
#include <thread>

std::string input = " ";

void getInterface() {
	while (input != "exit") {
		std::cout << ">";
		std::getline(std::cin, input);
	}
}

int main()
{

	std::cout << "This application will count in a " <<
		"separate thread in the background." << std::endl <<
		"Return 'current' for the updated total." << std::endl <<
		"Return 'exit' to terminate the application." <<
		std::endl << std::endl;

	std::thread interfaceThread(getInterface);
	interfaceThread.detach();

	for (long long int i = 0; input != "exit"; ++i) {
		if (input == "current") {
			std::cout << i << std::endl;
			input = " ";
		}
	}

	return 0;

}
Last edited on
if (input == "current") { ← Not thread safe at all. Imagine what will happens if you access input at the same moment it will be changed. You need to wrap your string in atomic or use mutexes to ensure that no races takes place. Please not thay you can add atomic only to integers and pointers.

As for globals:
a) (Preferable) You can pass value to thread by reference (of course thinking about thread safety too: wrap it in atomic or create you own locking class, example http://en.cppreference.com/w/cpp/thread/lock , http://en.cppreference.com/w/cpp/thread/unique_lock)
b) Limit variable visibility using static or unnamed namespaces.

You should avoid globals whenever possible, but I will not say that they should never be used. There is cases where using global variable is perfectly fine.
Last edited on
thanks for the reply. i will look into those things.
Topic archived. No new replies allowed.