c++ - 多次运行 pthread
问题描述
我希望一个线程运行无限次,以执行它接收到的 do_work() 函数中描述的任务。但是,该函数仅在 pthread_create() 子例程上调用。
我尝试在 while 循环中实现 sched_yield() 和 pthread_join() 例程。但它还没有奏效。
有没有可以再次调用现有线程的例程?
int main (int argc, char ** argv) {
int period;
int priority;
int load;
char schedule[15];
period = atoi(argv[1]);
priority = atoi(argv[2]);
load = atoi(argv[3]);
strncpy(schedule,argv[4],100);
std::cout << " period : " << period <<"\n priority : "<< priority << "\n load : "<< load << "\n schedule : " << schedule <<std::endl;
struct sched_param param;
pthread_t thread;
int rc;
sched_setscheduler (0, SCHED_FIFO , ¶m);
std::cout << "main() : creating thread " << std::endl;
rc = pthread_create(&thread, NULL, do_work, (void*)load);
if (rc) {
std::cout << "Error:unable to create thread " << rc << std::endl;
exit(-1);
}
int i=0;
struct sigaction action;
struct itimerval timer;
while(i<10000){
pthread_join(thread, NULL);
sched_yield();
i++;
}
pthread_exit(NULL);
}
解决方案
您不调用线程,而是创建线程。通过这样做,您指定了一个将在新线程中调用的start_routine 。
如果要在循环中重复调用函数,则可以在start_routine中执行以下操作:
void* start_routine(void *arg) {
while (active) { // active: atomic global boolean value
do_work();
}
// if no longer active,
// there could be an option to wait to become active again,
// or exit the thread
pthread_exit(NULL);
}
pthread_join()
仅在您想将线程与其他线程连接时才调用。pthread_join()
一直等到目标线程终止。通过加入线程,所有资源都归还给系统(清理)。
推荐阅读
- javascript - 如何引用映射数组的单个元素来呈现视图
- javascript - 如何从外部网站提取文章 URL 并将它们存储在列表/数组中?
- r - 在 R 中使用加权黄土插值时间序列
- plsql - 如何在 PLSQL 中将工作日添加到日期?
- node.js - 如何使用 Express 重新加载页面?
- dax - 一种使用同一表中的度量过滤一组不同列的方法 - Tabular2017
- db2 - 如何查看/读取 db2 日志?有没有办法以普通文本格式读取 db2 日志?
- css - 我的网站仅在移动设备上向右滚动,但只有空白
- javascript - 如何使用 Mysql2 Promise 结束数据库连接?
- azure - 如何从 CLI 在 Azure AD 中的 Azure 应用注册中生成客户端机密?