笔者今天来讲讲Linux下多线程的使用。
在之前的串口通信和网络通信中都使用到了多线程,今天就将这个碎碎念的多线程好好讲讲。
很多时候会遇到一些阻塞式的函数,比如select()函数(监测某个标示符是否发生变化(之前的串口或者网络通信标示符)),或者accept()函数,(等待客户端的连接),这些函数一直会等待,直到监测到发生变化或者客户端连接上,才退出,然后顺序执行后面的任务。
如果采用单任务执行,那这样阻塞严重影响其他任务的执行,所以这个时候就需要多任务处理(即"同时"执行很多个模块化程序,互不耽误)。笔者这里讲讲使用多线程来进行多任务处理。
注意注意:在编译的时候,如果使用多线程,要加上 -lpthread,
arm-linux-gnueabihf-gcc -g -c Mythread.c -o Mythread.o -lpthread
线程的创建函数 int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *),void *restrict arg );
参数1:线程ID
参数2:线程属性,默认NULL
参数3:线程开始的地址,即要执行的函数入口地址
参数4:若上述函数需要参数,将参数放入结构中并将地址作为arg传入。
如果返回值不等于0,则创建失败,否则创建成功。
线程结束:pthread_join(*pthread, NULL);
线程本身ID:pthread_self();
创建线程
int MyThreadStart(void*(*start_rountine)(void*),pthread_t *thread,void *arg)
{
memset(thread,0x00,sizeof(pthread_t));
int TempReturnValue;
TempReturnValue = pthread_create(thread,NULL,start_rountine,arg); //创建线程函数
if(TempReturnValue!=0)
{
printf("thread created failed!");
}
else
{
int id = pthread_self();
printf("thread id = %d",id);
}
return TempReturnValue;
}
结束线程
void MyThreadStop(pthread_t *pthread)
{
if(*pthread!=0)
{
pthread_join(*pthread, NULL);
printf("thread is over!");
}
}
线程上锁与解锁
为避免多个线程同时使用一块资源,比如同时操作一块内存空间,就会引发错误。所以线程在使用的资源的时候,一定要上锁,使用完成之后再解锁。
pthread_mutex_t CCURec_mutex_t = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&CCURec_mutex_t );
DeQueue(TempPlatformRecQueue,&TempData);
pthread_mutex_unlock(&CCURec_mutex_t );
闹钟函数
相当于定时器函数,signal()指明时间到了触发的函数,alarm()指明定时的时间。
void handler()
{
CCU_To_VST_IntersectionData();
alarm(T);
}
void TimerFunc()
{
signal(SIGALRM, handler); //注册定时器处理函数
alarm(T); //闹钟函数
}
实际调用三个线程函数运行一下:
int temp = MyThreadStart(pthread_NetRecFun_Platform,&PlatformRec_Id,&ArgPlatformRec);
if(temp == 0)
{
printf("PlatformRecfun threadFunc successfully!\n");
}
temp = MyThreadStart(pthread_NetSendFun_Platform,&PlatformSend_Id,&ArgPlatformSend);
if(temp == 0)
{
printf("PlatformSendfun threadFunc successfully!\n");
}
temp = MyThreadStart(pthread_NetProcessFun_Platform,&PlatformProcess_Id,&ArgPlatformProcess);
if(temp == 0)
{
printf("PlatformProcessfun threadFunc successfully!\n");
}
void *pthread_NetRecFun_Platform(void *arg); //socket通信 接收线程函数
void *pthread_NetSendFun_Platform(void *arg); //socket通信 发送线程函数
void *pthread_NetProcessFun_Platform(void *arg); //socket通信 解析线程函数