c++ - 从另一个线程杀死线程C++

标签 c++ multithreading

我是多线程新手,需要你的帮助。 考虑以下代码:

vector <int> vec; 
int j = 0;
void Fill()
{
    for (int i = 0; i < 500; i++)
    {
        Sleep(500);
        vec.push_back(i);
    }

}


void Proces()
{
    int count = 0;
    int n=-1;
    while (true) {
        Sleep(250);
        if (!vec.empty())
        {
            if (n != vec.back()) {
                n = vec.back();
                cout << n;
                count++;
            }
        }
        if (count == 101)break;
    }
}

void getinput()
{
    while (true) {
        int k=0;
        cin >> k;

            //if the user enters an integer i want to kill all the threads
    }
}
int main()
{
    thread t1(Fill);
    thread t2(Proces);
    thread t3(getinput);
    t1.join();
    t2.join();
    t3.join();
    cout << "From main()";


}

重点是我想从 t3(getinput) 中杀死 t1(Fill) 和 t2(Proces)。有没有办法做到这一点,如果有的话,请发布和示例。

最佳答案

使线程退出的常见方法是使用 ( atomic ) 标志,线程会检查该标志以确定是否应该退出。然后在外部设置这个标志,线程就会注意到它并自然退出。

类似于

#include <thread>
#include <atomic>
#include <iostream>
#include <chrono>

// Flag telling the thread to continue or exit
std::atomic<bool> exit_thread_flag{false};

void thread_function()
{
    // Loop while flag if not set
    while (!exit_thread_flag)
    {
        std::cout << "Hello from thread\n";
        std::this_thread::sleep_for(std::chrono::seconds(1));  // Sleep for one second
    }
}

int main()
{
    std::thread t{thread_function};  // Create and start the thread
    std::this_thread::sleep_for(std::chrono::seconds(5));  // Sleep for five seconds
    exit_thread_flag = true;  // Tell thread to exit
    t.join();  // Wait for thread to exit
}

关于c++ - 从另一个线程杀死线程C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48943929/

相关文章:

c++ - 到达for循环时出现奇怪的段错误

c++ - 如何调用模板化类型

python - 发生异常时停止线程

c# - 锁内的新线程 - C#

c++ - 如何开始用 C++ 编写音乐可视化工具?

C++多线程——初学查询

C++20 <chrono> 嵌套名称说明符中使用的不完整类型

android - I/Choreographer : Skipped 33 frames!应用程序可能在其主线程上做太多工作吗?

c++ - 如何使 libpcap/pcap_loop 成为非阻塞的?

调用一个线程并调用新程序 primeThreads.c