Fairly new.. Need help.

Hello!

I am fairly new to c++ & have a few questions.

I do not have a specific project I am currently working on, but I am trying to learn as much as I can about this before I start a project.

What I am wondering, is if I can have a color changing "title" that loops constantly while the program runs the rest of the functions..

Say I have my "title" (which i am just referring to the top line)
That says something like "Welcome to my program". I already have the code that will have it change colors constantly, but I want it to loop constantly while the program runs other functions.

Not sure if I am explaining clear enough, so if anyone can help or have questions of any further details, please help/ask.

Thank you
What you are looking for is called "Threads". It allows one to run multiple things in parallel. Maybe two loops in different functions at once.

Here is a quick demonstration (note you need a C++ 11 compatible compiler):
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
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <thread> //We need to include this to use multi-threading

void changeColour() //This will for example, change the colour of your title again and again
{
    std::string colours[] = {"Red", "Yellow", "Green", "Blue", "Orange"};
    //Keep changing the colour
    while(true)
    {
        std::cout << "Colour changed to " << colours[std::rand() % 5] << "!\n";
    }
}

void randomise() //This will make random numbers and print them
{
    while(true)
    {
        std::cout << "Random number is: " << std::rand() % 1000 << "\n";
    }
}

int main() //The main function
{
    std::srand(std::time(0)); //The random seed for getting random numbers with rand()

    std::thread thread_1(changeColour); //Create a new thread to use the changeColor() function
    std::thread thread_2(randomise); //Create a new thread to use the randomise() function
    
    //Here we continue doing our usual stuff
    while(true)
    {
        std::cout << "I'm the main thread.\n";
    }
    
    thread_1.join(); //Program will wait until thread_1 finishes, in this case never lol
    thread_2.join(); //Program will wait until thread_2 finishes, in this case never.
    
    return 0;
}


Observe the output closely. You will see that there are outputs from all three loops.

Refer to this link for more info:
http://www.cplusplus.com/reference/thread/thread/
Last edited on
I'd argue that multithreading in C++ is not a beginner topic. There are lots of nuances that are very easy to get wrong if you're not extremely careful.

Case in point... in Stormboy's extremely simplistic example... he does not do any synchornization, so if you do that code, you will get corrupted/unexpected output due to race conditions in your threads. You'll see things like:

Random number is: Color changed to: 63Blue
!
Color changed to: BlueRandom number is!
156
(etc)


Most of the time... updating multiple things "at once" is better accomplished serially rather than in parallel.



EDIT:

To elaborate... when I say "do things serially", I mean have one thread that switches between doing multiple things. Rather than creating a new thread for each thing you want to do.

A common pitfall for newbies is that they tend to make all of their code 'blocking'. This means it waits for some action to finish before allowing any further code to execute.

Here's an example (using WinAPI's 'Sleep' function. I'm too lazy to look up the C++11 equivalent... but hopefully you get the idea):

1
2
3
4
5
6
7
8
9
int main()
{
   // print a countdown:
   for(int x = 5; x >= 0; --x)
   {
       cout << x << endl;
       Sleep(1000);  // wait for 1 second.
   }
}


This will print a new number every second, until 0 is reached.

And while this works... it is blocking. Which means your program cannot do anything else while this countdown is happening.

A non-blocking approach would be to not Sleep... but instead periodically poll the time. Again I'm too lazy to look up the actual code for this so here is pseudo-code:

And I just slapped this together. This could probably be cleaner:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int main()
{
    int countdown = 5;
    cout << countdown << endl;

    auto lastPrintTime = getTheCurrentTime();

    while( countdown >= 0 )
    {
        // see if it has been a second since the last time we printed
        auto now = getTheCurrentTime();
        if( now - lastPrintTime > oneSecond )
        {
            // it has been... so count down
            --countdown;
            cout << countdown << endl;
            lastPrintTime = now;
        }

        // then do something else
        doSomethingElse();
    }
}


In this example... we have the same countdown... that waits 1 second between printing updates... but we're not blocked. doSomethingElse is repeatedly being called during the countdown, which will allow you to do something else while the countdown is happening.



It's all about shifting your design. Adding threads can be helpful in some situations, but usually they add a lot more complication and bugs than they're worth.
Last edited on
@ Disch: Yes multithreading indeed isn't a beginner's topic. But what the OP is looking to do is best done using threads.
Now that I read his topic again... yeah. My first advice would be "don't do that" and then my second advice would be "if you're going to do it, a separate thread would probably be easiest".

So yeah, you're right. In this case it does seem somewhat appropriate given the unlikelihood of the main thread messing with the title.

Sorry to step on your toes =) I just feel compelled to always give a cautionary warning to someone walking into multithreading for the first time. It's a minefield.
Topic archived. No new replies allowed.