Linux中的线程创建函数pthread_create函数

Linux系统中的多线程遵循POSIX线程接口,成为pthread。pthread_create函数用来创建一个用户线程,函数原型如下。

#include <pthread.h>

int pthread_create(pthread_t *restrict tidp,
                   const pthread_attr_t *restrict attr,
                   void *(*start_rtn)(void), 
                   void *restrict arg);

参数含义:
1)tidp参数表示指向线程标识符的指针。
2)attr参数用来设置线程属性,如果没有则填NULL。
3)start_rtn参数表示线程运行函数的地址。
4)arg参数表示线程运行函数的参数,如果没有参数则填NULL。

返回值:成功返回0,失败返回错误代码。

下面我们举个简单的例子,创建一个线程,主线程向新创建的线程传递一个参数,新线程中将参数打印,结束。

程序代码thread.c如下。

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

void *thread_func(void *arg)
{
	printf("arg = %d.\n", *((int *)arg));
	return NULL;
}

int main()
{
	int rc = 0;
	pthread_t tid;
	int arg = 233;
	printf("main thread.\n");
	rc = pthread_create(&tid, NULL, thread_func, &arg);
	if (rc)
		printf("ioctl: %s\n", strerror(errno));
	sleep(1);
	return rc;
}

这里需要注意一下,pthread_create调用后不能立刻return,这样线程创建和打印就会来不及运行就会结束主进程,所以要调用sleep函数让进程延迟一秒再结束。

编译该代码。含有线程的程序编译时需要调用静态链接库pthread,但pthread不是Linux系统的默认库,因此编译时需要加上-lpthread参数。

gcc thread.c -o thread -lpthread

运行结果如下。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值