linux进阶41——多线程程序设计(一):创建线程

创建线程

函数定义

#include <pthread.h>

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

返回值

成功返回0,失败返回错误编号。

参数

  • tidp:线程id;
  • attr:线程属性(通常为空);
  • start_rtn:线程要执行的函数,是一个函数指针;
  • arg:start_rtn的参数;

注意:因为pthread的库不是linux系统的库,所以在进行编译时要加上 -lpthread,格式如下:

gcc filename -lpthread

示例

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

void *testThread1(void)
{
	for(int i = 0; i < 5; i++)
	{
		printf("create 1st thread!\n");
		sleep(1);
	}
}

void *testThread2(void)
{
    for(int i = 0; i < 5; i++)
    {
        printf("create 2st thread!\n");
        sleep(2);
    }
}


int main()
{
	int ret = 0;
	pthread_t id1, id2;

	ret = pthread_create(&id1, NULL, (void*)testThread1, NULL);
	if(ret != 0)
	{
		printf("create thread1 error!\n");
		return -1;
	}

	ret = pthread_join(id1, NULL);
    if (ret != 0)
    {
        printf("join thread1 error\n");
        return -1;
    }

	ret = pthread_create(&id2, NULL, (void*)testThread2, NULL);
    if(ret != 0)
    {
        printf("create thread2 error!\n");
        return -1;
    }

	ret = pthread_join(id2, NULL);
    if (ret != 0)
    {
        printf("join thread2 error\n");
        return -1;
    }

	return 0;
}

编译运行:

[root@192 pthread]# gcc -lpthread pthread_create.c -o pthread_create
[root@192 pthread]# ./pthread_create
create 1st thread!
create 1st thread!
create 1st thread!
create 1st thread!
create 1st thread!
create 2st thread!
create 2st thread!
create 2st thread!
create 2st thread!
create 2st thread!
[root@192 pthread]# 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值