目录
调用多线程框架,在主函数写好环境监控文件的函数,使用结构体封装环境指标的参数
最后使用makefile管理工程文件
tasks.h
#include<pthread.h>
#ifndef __TASK_H__
#define __TASK_H__
typedef void* (*Thread_fun_t) (void *);//函数指针类型,指向返回值为void*,参数为void*的函数
typedef struct task
{
pthread_t tid;//线程的tid
Thread_fun_t pfun;//线程的函数
}Task_t;
extern int create_pthread_tasks(Task_t tasks[],int len);
extern void destroy_pthread_tasks(Task_t tasks[], int len);
#endif
type.h
#include<time.h>
#ifndef __TYPE_H__
#define __TYPE_H__
typedef struct env{ //用结构体封装环境指标参数
int devid;//设备id
float tmp;//温度
float hum;//湿度
float oxy;//氧气浓度
struct tm tim;//时间结构体
}Env_data_t;
#endif
main.c
#include<stdio.h>
#include <pthread.h>
#include<unistd.h>
#include<time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include"tasks.h"
#include"type.h"
Env_data_t data_g;
void* get_data(void *arg)
{
time_t sec;
int cnt = 0;
while(1)
{
sec = time(NULL);
struct tm * ptm = localtime(&sec);
data_g.devid = cnt++;
data_g.hum = 26.7;
data_g.oxy = 66.6;
data_g.tim = *ptm;
data_g.tmp = 36.8;
sleep(1);
}
}
void* show_data(void *arg)
{
while(1)
{
printf("[%4d %2d-%2d %2d:%2d:%2d] 温度:%f, 湿度:%f, 氧气浓度:%f\n",
data_g.tim.tm_year+1900, data_g.tim.tm_mon+1, data_g.tim.tm_mday,
data_g.tim.tm_hour, data_g.tim.tm_min, data_g.tim.tm_sec,
data_g.tmp,data_g.hum,data_g.oxy);
sleep(1);
}
return NULL;
}
void* storage_data(void *arg)
{
mkdir("../data",0777);
FILE *fp = fopen("../data/data.txt", "a");
if(NULL == fp)
{
perror("fail open data.txt!");
return NULL;
}
while(1)
{
fprintf(fp, "[%4d %2d-%2d %2d:%2d:%2d] 温度:%f, 湿度:%f, 氧气浓度:%f\n",
data_g.tim.tm_year+1900, data_g.tim.tm_mon+1, data_g.tim.tm_mday,
data_g.tim.tm_hour, data_g.tim.tm_min, data_g.tim.tm_sec,
data_g.tmp,data_g.hum,data_g.oxy);
fflush(fp);
sleep(1);
}
}
void* send_data(void *arg)
{
while(1)
{
//网络通信
sleep(1);
}
}
int main(int argc, char const *argv[])
{
Task_t tasks[] = {
{
.pfun = get_data,
},
{
.pfun = show_data,
},
{
.pfun = storage_data,
},
{
.pfun = send_data,
},
};
create_pthread_tasks(tasks, sizeof(tasks) / sizeof(tasks[0]));
destroy_pthread_tasks(tasks, sizeof(tasks) / sizeof(tasks[0]));
return 0;
}
tasks.c
#include"tasks.h"
#include<pthread.h>
#include<stdio.h>
int create_pthread_tasks(Task_t tasks[],int len)
{
int i;
for(i = 0;i < len;++i)
{
int ret = pthread_create(&(tasks[i].tid),NULL,tasks[i].pfun,NULL);
if(ret != 0)
{
printf("fail to pthread!\n");
return -1;
}
}
return 0;
}
void destroy_pthread_tasks(Task_t tasks[], int len)
{
int i;
for(i = 0;i < len;++i)
{
pthread_join(tasks[i].tid,NULL);
}
}
makefile
DST=app
SRC=main.c tasks.c
CC=gcc
FLAGS=-lpthread
INC=../include
$(DST):$(SRC)
$(CC) $^ -o $@ $(FLAGS) -I$(INC)
clean:
rm $(DST)