
1个回答
展开全部
用线程。 函数能否一直运行,要看函数的设计,要写成死循环就能一直运行下去。
第二个函数 每 隔一秒运行一次。你可以不用 线程。你写:
while(1) { Sleep(1000); bar( ); }; 那就不断调用bar()了。#include <windows.h> 就有 延迟函数 Sleep()。
#include <iostream>
#include <thread>
using namespace std;
void foo() {
// do stuff...
}
void bar( ) {
// do stuff...
}
int main()
{
std::thread first (foo);
std::thread second (bar,1);
std::cout <<"main, foo and bar now execute concurrently...\n";
// synchronize threads:
first.join();
second.join(); // 可以改用 while(1) { Sleep(1000); bar( ); };
std::cout <<"foo and bar completed.\n";
return0;
}
第二个函数 每 隔一秒运行一次。你可以不用 线程。你写:
while(1) { Sleep(1000); bar( ); }; 那就不断调用bar()了。#include <windows.h> 就有 延迟函数 Sleep()。
#include <iostream>
#include <thread>
using namespace std;
void foo() {
// do stuff...
}
void bar( ) {
// do stuff...
}
int main()
{
std::thread first (foo);
std::thread second (bar,1);
std::cout <<"main, foo and bar now execute concurrently...\n";
// synchronize threads:
first.join();
second.join(); // 可以改用 while(1) { Sleep(1000); bar( ); };
std::cout <<"foo and bar completed.\n";
return0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询