linux创建线程pthread_create函数

函数简介
  pthread_create是UNIX环境创建线程函数

头文件
  #include<pthread.h>

函数声明
  int pthread_create(pthread_t *restrict tidp,const pthread_attr_t restrict_attr,voidstart_rtn)(void),void *restrict arg);

返回值
  若成功则返回0,否则返回出错编号。

参数

第一个参数为指向线程标识符的指针。
  第二个参数用来设置线程属性。
  第三个参数是线程运行函数的地址。
  最后一个参数是运行函数的参数。

编译:

在编译时注意加上-lpthread参数,以调用静态链接库。因为pthread并非Linux系统的默认库

在Linux环境使GCC支持C99标准,使用如下命令编译(test_pthread2为c文件名字):
gcc test_pthread2.c -o test_pthread2 -std=c99 -pthread

pthread_join函数

函数简介
函数pthread_join用来等待一个线程的结束。

函数原型:
extern int pthread_join __P (pthread_t __th, void **__thread_return);

参数说明:
第一个参数为被等待的线程标识符,第二个参数为一个用户定义的指针,它可以用来存储被等待线程的返回值。这个函数是一个线程阻塞的函数,调用它的函数将一直等待到被等待的线程结束为止,
当函数返回时,被等待线程的资源被收回。如果执行成功,将返回0,如果失败则返回一个错误号。

下面通过一个demo来说明这两个接口函数的用法:

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

struct pthread_variable
{
	int number;
	char *name;
}; 

void *create_pthread(void *arg)//有void* 型参数传入,不能直接void, void*表示任何类型的参数 
{

	struct pthread_variable *temp;
	temp=(struct pthread_variable *)arg;//通过指针赋地址给结构体变量赋值 
        printf("pthread_variable->number: %d\n", temp->number);
        printf("pthread_variable->name: %s\n", temp->name);

	sleep(1);

	return (void *)3; //返回一个指向void的数据类型的值
}

int main(int argc, char **argv)
{

	pthread_t pthread_test;//定义线程标识符

	struct pthread_variable *var;
	void* pthread_return;

	var =(struct pthread_variable *)malloc(sizeof(struct pthread_variable));// 分配内存空间 

	var->number = 99; //结构体成员赋值
	var->name = "czd";              

	if((pthread_create(&pthread_test, NULL, create_pthread, (void*)var)) == -1) //pthread_create创建线程
	{
		printf("create pthread error!\n");
		return 1;
	}

	if(pthread_join(pthread_test, &pthread_return)) //调用pthread_join函数,等待线程结束再继续往下执行
	{
		printf("thread is not exit...\n");
		return -2;
	}

	printf("thread is exit , is %d\n",(int)pthread_return); //打印线程结束的返回值pthread_return
	return 0;

}

编译执行
在linux环境下执行编译(test_pthread2.c为c文件名,编译生成bin文件:test_pthread2 ):
gcc test_pthread2.c -o test_pthread2 -std=c99 -pthread

运行该bin文件:

zwei@ubt144c:/work/zwei/czd/others/pthread$ ./test_pthread2
pthread_variable->number: 99
pthread_variable->name: czd
thread is exit , is 3
zwei@ubt144c:/work/zwei/czd/others/pthread$
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

零意@

您的打赏将是我继续创作的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值