linux下的线程操作

linux下的线程操作

一、函数原型

线程头文件
#include<pthread.h>
函数原型
1.创建线程
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
参数:
thread:用于返回创建的线程的ID
attr:线程属性,一般设置为NULL
start_routine: 这是一个函数指针,指向线程被创建后要调用的函数
arg:用于给线程传递参数,如果没有传递参数就置NULL
返回值:成功 0,错误 故障号

2.线程等待
int pthread_join(pthread_t thread, void **retval);
参数:thread:线程号
retval: 用户定义的指针,用来存储被等待线程的返回值。
返回:成功0,失败 故障号

pthread_join使一个线程等待另一个线程结束。
代码中如果没有pthread_join主线程会很快结束从而使整个进程结束,从而使创建的线程没有机会开始执行就结束了。加入pthread_join后,主线程会一直等待直到等待的线程结束自己才结束,使创建的线程有机会执行。
所有线程都有一个线程号,也就是Thread ID。其类型为pthread_t。通过调用pthread_self()函数可以获得自身的线程号。

编译需要添加-lpthread
例如:gcc main.c -o main -lpthread

二、示例

#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
void *myth1(void *ptr)
{
	printf("th1 is created\n");
	while(1)
	{
		printf("th1 is running\n");
		usleep(100000);//delay 100ms
	}
}

void *myth2(void *ptr)
{
	printf("th2 is created\n");
	while(1)
	{
		printf("th2 is running\n");
		sleep(1);//1s
	}
}
int main()
{
	pthread_t th1,th2;
	int pid1,pid2;
	//create pthread
	pid1 = pthread_create(&th1,NULL,myth1,NULL);
	if(pid1 != 0)
	{
		printf("create pthread 1 error\n");
	}
	//create pthread
	pid2 = pthread_create(&th2,NULL,myth2,NULL);
	if(pid2 != 0)
	{
		printf("create pthread 2 error\n");
	}
	//wait pthread
	pthread_join(th1,NULL);
	pthread_join(th2,NULL);
	return 0;
	
}

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值