C/C++ 多线程时,运行时输入自定义参数,达到控制线程的目的
基础概念
线程:线程是操作系统能够进行运算调度的最小单位,它被包含在进程之中,进程包含一个或者多个线程。进程可以理解为完成一件事的完整解决方案,而线程可以理解为这个解决方案中的的一个步骤,可能这个解决方案就这只有一个步骤,也可能这个解决方案有多个步骤。
多线程:多线程是实现并发(并行)的手段,并发(并行)即多个线程同时执行,一般而言,多线程就是把执行一件事情的完整步骤拆分为多个子步骤,然后使得这多个步骤同时执行。
C++多线程:(简单情况下)C++多线程使用多个函数实现各自功能,然后将不同函数生成不同线程,并同时执行这些线程(不同线程可能存在一定程度的执行先后顺序,但总体上可以看做同时执行)。
如何在多线程时通过自定义参数控制程序退出,或者进行切换功能
如下提供了一个demo以供参考
#include <pthread.h>
#include <iostream>
using namespace std;
atomic<bool> bQuit;
int main()
{
thread([&]
{
pthread_setname_np(pthread_self(), "RuntimeMenu");
while (!bQuit)
{
cout << "Enter q to quit this app" << endl;
cout << "Enter r to print run your function " << endl;
char line[256];
cout << "-\n";
cin.getline(line, 256);
if (line[0] == 'q') {
cout << "Now , quit the thread ! ! !" << endl;
bQuit = true;
}
if (line[0] == 'r')
{
cout << "your function is running"<<endl;
/* do your function*/
}
}
}).detach();
while (!bQuit)
{
cout << "this is main function" << endl;
sleep (3);
}
return 0;
}