【Linux多线程编程-自学记录】02.创建线程

Linux多线程编程学习代码记录(代码已上传gitee,点个Star也不错哦!)
https://gitee.com/chenshao777/linux_thread.git

【Linux多线程编程-自学记录】
       01.线程ID与进程ID
       02.创建线程
       03.主线程与子线程生命周期
       04.线程链接-pthread_join
       05.取消线程
       06.向线程发送信号-sigaction
       07.线程清除
       08.Linux多线程互斥量
       09.Linux多线程之读写锁
       10.条件变量


02.创建线程

笔记:
int pthread_create(pthread_t*restrict thread,
                  const pthread_attr_t *restrict attr,
                  void *(*start_routine)(void *),
                  void *restrict arg)
第一个参数: 新线程的id,如果成功则新线程的id回填充到tidp指向的内存
第二个参数: 线程属性(调度策略,继承性,分离性…)
第三个参数: 回调函数(新线程要执行的函数)
第四个参数: 回调函数的参数
返回值: 成功返回0,失败则返回错误码

编译时需要连接库pthread

错误码查看
cat /usr/include/asm-generic/errno.h

spu.h文件

#ifndef _SPU_H_
#define _SPU_H_

#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>

#endif

02.create_pthread.c文件

#include "spu.h"

void print_id(char *str)
{
	pid_t pid;
	pthread_t tid;
	
	pid = getpid();
	tid = pthread_self();
	printf("%s pid = %u, tid = 0x%x\n", str, pid, tid);
}

void *thread_fun(void *arg)
{
	print_id(arg);
	//return (void*)0;
}

int main()
{	
	int err;
	pthread_t thread_id;

	err = pthread_create(&thread_id, NULL, thread_fun, "new thread");
	if(err != 0)
		printf("create fail, err = %d\n",err);
	else
		printf("create success!\n");

	sleep(1);
	print_id("main_id: ");

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值