12 多线程编程
说明¶
由于我们需要使用的任务比较多,所以我们使用C语言的多线程编写。由于是初次使用,我们先简单写一个案例测试。
本实验分两个线程任务,按键检测线程和dht11数据获取线程。
按键检测线程:通过按键值,判断LED的亮灭。
dht11数据获取线程:获取DHT11的数据,并进行打印。
编程¶
创建两个线程任务,分文件编写。
首先是thread_key.c。要使用指针函数的方式,然后parameter是传入的变量,这里未处理。
#include "thread_key.h"
#include "bsp_key.h"
#include "bsp_led.h"
void *thread_key(void *parameter)
{
int key_value = 0;
led_init();
key_init();
while (1)
{
key_value = KeyScan(SINGLE_SCAN); //读取引脚电平
if(key_value == 1)
{
led_all_on();
}else if(key_value == 2 || key_value == 3)
{
led_all_off();;
}
delay(5);
}
}
然后是thread_dht11.c
#include "thread_dht11.h"
#include "dht11.h"
void *thread_dht11(void *parameter)
{
uint8_t RH=0,TMP=0;
int ret = 0;
int thread_count = 0;
dht11_init();
printf("Starting...\n");
while (1)
{
ret = get_dht11_data(&RH,&TMP);
if(ret == 0)
{
thread_count ++;
printf("RH:%d TMP:%d thread_count:%d\n",RH ,TMP,thread_count);
}
delay(1000);
}
}
线程任务写完后,我们就在主函数,创建这两个线程,并将他们跑起来
#include <wiringPi.h>
#include "thread_key.h"
#include "thread_dht11.h"
#include <pthread.h>
pthread_t keyThread; //按键线程
pthread_t dht11Thread; //dht11线程
int main(void)
{
if (-1 == wiringPiSetupGpio()) {
printf("Setup wiringPi failed!");
return 1;
}
pthread_create(&keyThread, NULL, thread_key, NULL); // 按键线程创建
pthread_create(&dht11Thread, NULL, thread_dht11, NULL); // dht11线程创建
pthread_join(keyThread, NULL); // 调用pthread_join函数,使主线程阻塞并等待keyThread标识的线程执行完毕
pthread_join(dht11Thread, NULL);
return 0;
}
我的代码里面将他分文件编写,同时处理的编号为BCM编号,其他未作处理,直接编译即可。
想要停止这个程序,Ctrl+c即可。 以上,就是一个简单的多线程任务处理。