如果每个线程都需要无限循环执行 DoingSomethingWithResource() 和 DoingSomethingWithoutResource(),可以使用如下的代码示例:
#include <iostream>
#include <thread>
void DoingSomethingWithResource()
{
while (true) {
// 执行持有资源时的任务
std::cout << "Thread with resource is doing something..." << std::endl;
// 模拟持有资源处理时间
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
void DoingSomethingWithoutResource()
{
while (true) {
// 执行不持有资源时的任务
std::cout << "Thread without resource is doing something..." << std::endl;
// 模拟不持有资源处理时间
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main()
{
std::thread t1(DoingSomethingWithResource);
std::thread t2(DoingSomethingWithoutResource);
std::thread t3(DoingSomethingWithoutResource);
t1.join();
t2.join();
t3.join();
return 0;
}
在上述示例中,每个线程通过一个无限循环来一直执行 DoingSomethingWithResource() 或 DoingSomethingWithoutResource() 中定义的任务。请注意,这种情况下没有使用条件变量或互斥锁进行线程间同步,因此需要确保任务本身是线程安全的,以避免数据竞争等问题。同时也要注意,在无限循环中适当地加入睡眠操作(如std::this_thread::sleep_for())来控制线程的执行速度,以免造成资源过度占用。
内容由零声教学AI助手提供,问题来源于学员提问




