C 构建控制台服务器日志 命令



你好,我想在C 中构建控制台服务器。它必须编写其他线程的输出,但也会收到命令我能怎么做?我敢肯定我的示例是错误的:/因为CIN都阻止了所有...

static string output = "";
//The function we want to make the thread run.
void task1(string msg){
    for (int i= 0; i < 10; i++)
        output += "task1 says: " + msg + "n";
}
void task2(string msg){
    char c;
    cout << output << endl << "_> ";
    output = "";
    cin >> c;
    cout << endl;
}
int main(){
    // Constructs the new thread and runs it. Does not block execution.
    thread t1(task1, "Hello");
    thread t2(task2, "Hello");
    //Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
    t1.join();
    t2.join();
    char c;
    cin >> c;
    return 0;
}

首先,您有种族条件,这两个线程都可以同时修改output变量。

对于另一个问题,您需要使用低杠杆平台的特定功能来检查是否准备从标准输入中读取输入,并且您可能需要使用较低级别的非阻滞功能来读取该输入也是如此。在POSIX系统(例如Linux或OSX)上,您可以使用例如fcntl制作STDIN_FILENO(标准输入文件描述符)非块,然后 select和poll和 read读取。

最新更新