像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文件中,编译后生成的可执行文件,在终端打开后作为一个独立的进程运行,然后该进程创建了三个线程(任务),最后进入死循环,三个线程运行。