rick
rick

Reputation: 931

Doing multiple jobs at the same time in C++

I have made a login Command Line interface in C++ where a marquee will run for indefinite time and in the next line a user can enter his id and password. I want both these work i.e. marquee and id input at the same time but with the below code only marquee is running for infinite time. I am using windows OS and i am new to C++ so I am not able to apply thread concepts.

char m[]={"- A cool marquee effect. Programmed by Roneet -"};
int main()
{
    marquee();
    cout<<setw(35)<<"Enter Username : ";
    getline(cin,str);
    cout<<setw(35)<<"Enter Password : ";

    return 0;
}
void marquee()
{
    while(a<131)
    {
        p=m[0];
        m[0]=m[c];
        m[c]=p;
        for(j=1;j<=b;j++)
            cout<<m[j];
        for(j=0;j<N;j++){}
        c--;
        cout<<"\r";
        if(c<1){c=b;a++;if(a==100)N=51500;}
    }
    system("PAUSE");
}

Upvotes: 1

Views: 260

Answers (1)

Piotr Skotnicki
Piotr Skotnicki

Reputation: 48447

First of all, std streams are not thread safe, you need to add std::mutex to protect each std::cout operation.

Secondly, to easily execute a function in a separate thread, use std::async

#include <future>

std::future<void> fut = std::async(&marquee);

Example:

#include <atomic>
#include <future>
#include <string>
#include <iostream>

std::atomic<bool> cond{ false };

void marquee()
{
    while (!cond)
    {
        std::cout << '*' << std::flush;
    }
}

int main()
{
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cerr.tie(nullptr);

    std::cout << "Enter username and then password: " << std::flush;

    std::future<void> task = std::async(std::launch::async, &marquee);

    std::string user, pass;
    std::cin >> user >> pass;

    cond = true;

    task.get();

    return 0;
}

Upvotes: 1

Related Questions