使用线程(使用,创建等)使线程在主线程上运行

时间:2016-11-12 00:32:55

标签: c++ multithreading

我试图在没有中断cout的情况下运行cin(例如对话或说明)。

如果你只做cin>>一个;当你的cout正在运行它时,它暂停代码等待用户输入,所以我被引导到一个新的线程,因为我是新的,这是我第一次使用线程最终搞清楚我仍然有一个问题,它在完成if语句(退出)之前等待主线程完成,但它会立即给出cout。

感谢任何帮助。

#include <QCoreApplication>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include <cstdlib>
#include <thread>
#include <unistd.h>
#include <cstdlib>
using namespace std;


string typesome;
thread function1;

void function_1()
{
    //cout << "I am Running.. - CIN";
    getline(cin, typesome);
   //std::thread relc(releasecin, getline(cin, typesome));
    if (typesome == "you good cuz")
{
    cout << "You typed " << typesome << " I will stop\n";
    system("exit");
}
    else
{
    cout << "this is my story\n";
}

};

int main(void)
{

    std::thread t1(function_1); // Start the CIN
   // t1.join(); // Waits for the CIN to load
    cout << "Hey type something while i talk\n";
    usleep(10000000);
    cout << "I am a nice person\n";
    cout << "I like pie\n";
    usleep(10000000);
    cout << "At any time if i get out of line just type you good cuz to stop me\n";
    if (typesome == "you good cuz")
    cout << "You typed " << typesome << " I will stop";
    else
    cout << "this is my story\n";
    usleep(10000000);
    cout << "West philly born and raised\n";


    return 0;

}

1 个答案:

答案 0 :(得分:0)

我找到了一种方法来实现这一点,只需在线程中加入一段时间,所以当getline是正确的单词时,它会切换到while循环,忘记main,我想出了线程和所有这些!