c ++:使用多线程在控制台中移动光标

c++: move cursor in console with multithreading

我在 Mac 系统下 xcode 工作。

我想用 C++ 在控制台中模拟 falling code

我的设计是每一个落下的代码链都是一个对象,里面有一个包含系统的函数API移动光标。通过多线程,我可以模拟一些下降的代码链。

这是我的代码:

// CodeChain.h
class CodeChain
{
public:
    CodeChain(int, int);
    void setx(int);
    void sety(int);
    void show();
    std::thread threadShow();
private:
    char codes[256];
    int x, y;
};


//CodeChain.cpp
CodeChain::CodeChain(int ax, int ay) : x(ax), y(ay)
{
    codes[0] = 'a';
    codes[1] = 'b';
    codes[2] = 'c';
    codes[3] = 'd';
    codes[4] = '[=10=]';
}

void CodeChain::show()
{
    int i = 0;
    char ch;
    int n = 0;
    while (true) {
        move(x + n - 1, y);
        printw("%c", ' ');
        i = 0;
        while ((ch = codes[i]) != '[=10=]') {
            move(x + i + n, y);
            printw("%c", ch);
            ++i;
        }
        n++;
        refresh();
        sleep(1);
    }
}

std::thread CodeChain::threadShow()
{
    return std::thread([=] { show(); });
}


void CodeChain::setx(int ax)
{
    x = ax;
}

void CodeChain::sety(int ay)
{
    y = ay;
}


// main.cpp
int main(int argc, char *argv[]) {   
    initscr();
    start_color();

    CodeChain cc0(5, 1);
    CodeChain cc1(5, 2);

    std::thread t0 = cc0.threadShow();
    std::thread t1 = cc1.threadShow();

    t0.join();
    t1.join();


    return 0;
}

如果CodeChain只有一个对象,也就是说只有一个线程运行,就可以。我可以看到一个下降的代码链。

但是,如果我添加一个线程,就像上面的代码一样,所有的东西都会聚集起来。我到处都能看到代码。好像我遇到了同步问题,但我想不通。

move(x + i + n, y)
printw("%c", ch);

这两行必须锁定。否则会出现同步问题