像RTOS一样进行Linux的pthread多线程编程

像RTOS一样进行Linux的pthread多线程编程

举一个简单的例子,话不多说,上代码

#include <stdio.h>
#include <unistd.h>
#include <stdint.h>
#include <pthread.h>


pthread_t MyTaskID_01, MyTaskID_02, MyTaskID_03;         // 线程句柄

void *MyTask1(void *arg)       
{
    uint8_t  count = 1;
    while( 1 )
	{
		usleep(1000*1000);
    	printf("\r\n线程1已经运行%d次...\r\n", count++);
	}
}

void *MyTask2(void *arg)         
{
    uint8_t  count = 1;
	while( 1 )
	{
    	usleep(2000*1000);
    	printf("\r\n线程2已经运行%d次...\r\n", count++);
	}
}

void *MyTask3(void *arg)         
{
    uint8_t  count = 1;
	while( 1 )
	{
		usleep(3000*1000);
		printf("\r\n线程3已经运行%d次...\r\n", count++);
	}
}


int  main(  )
{
	int res;

	/* 创建线程 */
	if( ( res = pthread_create( &MyTaskID_01,  0,  MyTask1,  NULL ) ) != 0 )
		printf("线程1创建失败!\n");
	else
		printf("线程1创建成功\n");

	if( ( res = pthread_create( &MyTaskID_02,  0,  MyTask2,  NULL ) ) != 0 )
		printf("线程2创建失败");
	else
		printf("线程2创建成功\n");
        
	if( ( res = pthread_create( &MyTaskID_03,  0,  MyTask3,  NULL ) ) != 0 )
		printf("线程3创建失败");
	else
		printf("线程3创建成功\n");

	/* 进程挂机 线程开始运行 */
	while(1); 
}

上面这些代码写到一个C文件中,编译后生成的可执行文件,在终端打开后作为一个独立的进程运行,然后该进程创建了三个线程(任务),最后进入死循环,三个线程运行。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值