Linux多线程编程——C语言常用函数及代码

1. 函数介绍

  1. int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg)        线程创建函数
    • thread,传出参数,用来接收线程id
    • attr,线程属性设置
    • start_routine,回调函数,告诉线程应该做的事情
    • arg,回调函数的参数
  2. void pthread_exit(void *retval);        线程返回函数(若在子线程使用,可传递返回值,若在主线程中使用,可等待其他线程执行结束再释放进程资源)
    • retval,传出参数,配合pthread_join接收子线程返回值
  3. int pthread_join(pthread_t thread, void **retval);      线程回收函数,阻塞,直到thread子线程执行结束
    • thread,等待的子线程号
    • retval,接收pthread_exit中的返回值
  4. int pthread_detach(pthread_t thread);          线程分离函数,将主线程与子线程分离,子线程资源不需要主线程调用pthread_join回收释放
    • thread,分离的子线程号
  5. int pthread_cancel(pthread_t thread);        线程取消函数,主线程用于取消一个子线程,取消后子线程并不会立刻结束运行,而是等到子线程下一次执行系统调用时才会被kill
    • thread,要取消的子线程号

2. 代码例程

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

struct Test
{
	int num;
	int age;
};

void *callback(void* arg)
{
	for(int i=0; i<5; i++)
	{
		printf("子线程: i = %d\n", i);
		//sleep(1);
	}
	printf("子线程: %ld\n", pthread_self());
	
	((struct Test*)arg)->num = 100;
	((struct Test*)arg)->age = 6;
	
	pthread_exit(NULL);
}
int main()
{
	pthread_t tid;
	struct Test t;
	pthread_create(&tid, NULL, callback, &t);
	
	printf("主线程:%ld\n", pthread_self());
	
	pthread_detach(tid);
	pthread_exit(NULL);	// 不会释放进程空间
	return 0;
}

输出:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值