pthread_create函数

线程创建函数

 与创建进程不同,创建线程时可以指定一个工作函数,新线程将从这个函数开始执行,函数返回也就等价于线程退出。

工作函数必须有一个(void *)型参数,新线程开始执行时,这个参数的值就是pthread_create函数的arg参数的值,因此可以利用它来向线程传递数据。

工作函数必须有(void *)型的返回值,它代表线程的退出状态。

注意:任意线程调用exit()都会终止整个进程示例如下;初始线程从main()函数返回时(return)整个进程也将终止。 

例程如下:

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

int a = 1;

void *create(void *arg)
{
	printf("pthread a: %d\n",a);
	a++;
	printf("num = %s\n",(char *)arg);

	//return (void *)0;
	pthread_exit((void *)0);
}

int main()
{
	int a = 3;
	char *ptr="helloworld";
	int test = 4;
	pthread_t pid;
	printf("main 1 a: %d\n",a);
	if(-1 == pthread_create(&pid,NULL,create,(void *)ptr))//第四个参数是实参地址
	{
		perror("pthread_create");
		exit(1);
	}
	void *status;
	pthread_join(pid,&status);			//阻塞 等待线程结束   回收线程资源
	printf("main 2 a: %d\n",a);
	
    return 0;
}

   

执行结果如下:

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

参数说明:

thread           :线程id(由系统自动分配然后返回)

attr               :线程属性(通常为空NULL)

start_routine  :线程要执行的函数名

arg               :函数实际参数的地址

返回:成功0,失败-1

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值