Linux下C语言编程(5):多线程编程

笔者今天来讲讲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通信  解析线程函数

在这里插入图片描述
在这里插入图片描述
上一篇:Linux下C语言编程(4):TCP/IP 网络通信

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张一西

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值