C语言学习之线程

(一)函数

  1. #include <pthread.h>
    int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
    功能:创建一个新的线程
    参数:
    thread 将新线程的id存储到这个地址空间里
    attr NULL 使用缺省的属性
    start_routine 函数指针 存放函数的入口地址 线程函数的入口地址
    arg 传递给线程函数的唯一参数
    返回值:
    成功 0
    错误 非0的错误码 errno被设置
     
    Compile and link with -pthread.
    void *(*start_routine) (void *)

  2. #include <pthread.h>
    pthread_t pthread_self(void);
    功能:获取当前线程的id
    返回值:
    返回当前线程的tid unsigned long

  3. #include <pthread.h>
    void pthread_exit(void *retval);
    功能:终止当前线程
    参数:
    retval 将该指针的值传递给进程中调用pthread_join(3)的另外一个线程,所以接收该值时,用二级指针作为形参接收

  4. #include <pthread.h>
    int pthread_detach(pthread_t thread);
    功能:分离一个线程
    参数:
    thread 指定要被分离的线程的id
    返回值:
    成功 0
    错误 非0的错误码
    如果将线程设置为分离状态,线程终止的时候,自动将资源释放给系统

  5. #include <pthread.h>
    int pthread_join(pthread_t thread, void **retval);
    功能:阻塞等待汇合一个线程,等该线程终止
    参数:
    thread 指定了要汇合的线程的tid 线程必须是可汇合的线程
    retval 将可汇合线程的退出状态码拷贝到retval中.
    如果可汇合的线程是取消的线程.将PTHREAD_CANCELED拷贝到
    retval中
    返回值:
    成功 0
    错误 非0的错误码
    汇合:一个线程(这个线程必须是可汇合的线程)终止以后,同一个进程中的另外一个线程回收终止线程的资源

  6. #include <pthread.h>
    int pthread_cancel(pthread_t thread);
    功能:给指定的线程发送取消请求
    参数:
    thread 指定要取消的线程的id
    返回值:
    成功 0
    错误 非0的错误码

(二)代码

#include <t_stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>


void *thr_func1(void *arg){
	printf("thr_func1 running...\n");
	return (void *)1l;
}

void *thr_func2(void *arg){
	printf("thr_func2 running...\n");
	pthread_exit((void *)2l);
}

void *thr_func3(void *arg){
	while(1){
		printf("thr_func3 running...\n");
		sleep(1);
	}
	return NULL;//永远不可能执行到
}

int main(void){
	void *ret;
	//创建一个新的线程
	pthread_t tid;
	pthread_create(&tid, NULL, thr_func1, NULL);
	//阻塞等待新线程的终止,汇合新线程
	//将新线程的退出状态码(或返回值)保存到ret中
	pthread_join(tid, &ret);
	printf("thr_func1 exit code...%ld\n", (long)ret);


	//创建一个新的线程
	pthread_create(&tid, NULL, thr_func2, NULL);
	//阻塞等待新线程的终止,汇合新线程
	//将新线程的退出状态码(或返回值)保存到ret中
	pthread_join(tid, &ret);
	printf("thr_func2 exit code...%ld\n", (long)ret);


	//创建一个新的线程
	pthread_create(&tid, NULL, thr_func3, NULL);
	sleep(5);
	//给指定tid的线程发出取消请求
	pthread_cancel(tid);
	//阻塞等待新线程的终止,汇合新线程
	//将新线程的退出状态码(或返回值)保存到ret中
	pthread_join(tid, &ret);
	if(ret == PTHREAD_CANCELED)
		printf("thr_func3 exit code...%ld\n", (long)ret);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值