Linux多线程编程之pthread

本文详细介绍了Linux下使用pthread进行多线程编程,包括线程创建、线程等待、线程分离和线程终止。通过pthread_create创建线程,pthread_join等待线程结束,pthread_detach实现资源自动回收,以及pthread_exit和pthread_cancel用于线程的正常或异常终止。示例代码展示了函数的具体使用方法。
摘要由CSDN通过智能技术生成


头文件:#include <pthread.h>
在编译时注意加上-lpthread参数,以调用动态链接库。因为pthread并非Linux系统的默认库。

1.线程创建

函数声明

int pthread_create(pthread_t * thread, const pthread_arrt_t* attr,void*(*start_routine)(void *), void* arg);

-thread:指向线程标识符的指针
-attr:线程的属性。给传递NULL表示设置为默认线程属性
-start_routine:线程执行实体入口
arg:运行函数的参数
-返回值:成功返回0,失败返回错误码
-typedef unsigned long int pthread_t

线程id的类型是pthread_t,它只在当前进程中保证是唯一的,在不同的系统中pthread_t这个类型有不同的实现,调用pthread_self()可以获得当前线程的id.

代码演示:

#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<errno.h>
#include<unistd.h>

void* thread_start(void* arg){
   
	
	int arg_data = *((int*)arg);
	for (int i = 0; i < 10; i++){
   
		//这里要注意一下
		//当创建一个线程之后,该线程和主线程一起执行,若主线程提前退出了,thread_start这个线程还没有来得及打印也会因为主线程退出而退出了
		for (int j = 0; j < 5000000; j++);
		printf("Receive arg %d=%d\n", arg_data, arg_data);
	}
}
int main(void){
   

	pthread_t tid ;
	int arg1 = 1;
	int arg2 = 2;
	//创建线程
	int ret = pthread_create(&tid, NULL, thread_start, (void*)&arg1);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值