gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:37:50 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com