//周期性任务的线程正在无限循环中运行。我已经包含了一个标志和sleep(),以便它仅执行一定时间,然后进入睡眠状态。但是,修改之后,我根本没有得到输出“执行线程”。请提出建议,如何修改睡眠功能的用法,以便获得时间“执行线程”的输出,然后进入睡眠状态。//
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <unistd.h>
int exitflag=0;
struct task_spec_struct
{
char task_type;
int period,r_min,r_max;
}s1;
int gen_rand(int a, int b)
{
srand(time(NULL));
int x = a+(rand()%(b-a));
return x;
}
//task body to utilize CPU to perform computations
void* periodic_task(void* arg)
{
struct task_spec_struct *arg_struct = (struct task_spec_struct*) arg;
int rand_num = gen_rand(arg_struct->r_min, arg_struct->r_max);
while(1)
{
int i, j=0;
for(i=0; i<rand_num; i++)
{
j=j+i;
}
if (exitflag==1)
{
pthread_exit(0);
}
usleep((arg_struct->period)*1000);
printf("Executing thread1");
}
//pthread_exit(0);
}
int main(int argc, char **argv)
{
int num_args = argc-1;
// Creating pthread for periodic task ( runs Thread function to run periodically)
// printf("\nGive task with specifications:");
s1.task_type= 'P';
s1.period= 300;
s1.r_min= 400;
s1.r_max= 500;
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&tid, &attr, periodic_task, &s1);
int ret=sleep(3);
if (ret==0)
{
exitflag=1;
}
pthread_join(&tid, NULL);
}
答案 0 :(得分:0)
printf默认情况下不会刷新,除非您以换行符结束字符串。参见Why does printf not flush after the call unless a newline is in the format string?。
您没有看到输出,因为未刷新缓冲区。添加新的换行符,或在stdout上调用fflush。